How to convert a BsonDocument into a strongly typed object with the official MongoDB C# driver?

前端 未结 4 1018
我寻月下人不归
我寻月下人不归 2021-02-05 05:15

For unit testing purposes, I\'d like to test my class mappings without reading and writing documents into the MongoDB database. To handle special cases such as circular parent

4条回答
  •  野性不改
    2021-02-05 05:59

    Use yield keyword to return data as you want.

    public IEnumerable GetMongoFields(string collectionName)
            {
                var connectionString = ConfigurationManager.ConnectionStrings[DbConfig.GetMongoDb()].ConnectionString;
                var databaseName = MongoUrl.Create(connectionString).DatabaseName;
                MongoClient client = new MongoClient(connectionString);
                var server = client.GetServer();
                var db = server.GetDatabase(databaseName);
    
                var collection = db.GetCollection(collectionName);
                var list = collection.FindAll().ToList();
    
               yield return list.ToJson();
            }
    

提交回复
热议问题