mongodb Helper
/// <summary> /// mongoDBHelper访问助手 /// </summary> public class mongoDBHelper { /// <summary> /// 将json字符串序列化为 文档对象 /// </summary> /// <param name="json"></param> /// <returns></returns> public static BsonDocument getDocFromJson(string json) { BsonDocument document = BsonSerializer.Deserialize<BsonDocument>(json); return document; } public async static void Test() { try { //建立连接 var client = new MongoClient("mongodb://localhost:27017"); //获取数据库 var database = client.GetDatabase("foo"); //获取集合 var collection = database.GetCollection<BsonDocument>("bar"); //创建文档 var document = new BsonDocument() { { "name", "MongoDB" }, { "type", "Database" }, { "count", 1 }, { "info", new BsonDocument{ { "x", 203 }, { "y", 102 } } } }; //向集合添加文档 await collection.InsertOneAsync(document); //查询数据 - 单个条件 { var filter = Builders<BsonDocument>.Filter.Eq("i", 71); var docResult = collection.Find(filter).ToCursor(); foreach (var doc in docResult.ToEnumerable()) { Console.WriteLine(doc); } } //查询数据 - 多个条件 { var filterBuilder = Builders<BsonDocument>.Filter; var filter = filterBuilder.Gt("i", 50) & filterBuilder.Lte("i", 100); var docResult = collection.Find(filter).ToCursor(); foreach (var doc in docResult.ToEnumerable()) { Console.WriteLine(doc); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }