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

前端 未结 4 1024
我寻月下人不归
我寻月下人不归 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:52

    A straight forward way if you want to map rows fetched from mongoDB to a class within your code is as below

    //Connect and Query from MongoDB
    var db = client.GetDatabase("blog");
    var col = db.GetCollection("users");
    var result = await col.Find(new BsonDocument("Email",model.Email)).ToListAsync();
    
    //read first row from the result
    var user1 = result[0];
    result[0] would be say "{ "_id" : ObjectId("569c05da09f251fb0ee33f5f"), "Name" : "fKfKWCc", "Email" : "pujkvBFU@kQKeYnabk.com" }"
    
    // a user class with name and email
    User user = new User();
    
    // assign 
    User.Name = user1[1].ToString();      // user1[1] is "fKfKWCc"    
    User.Email = user1[2].ToString();      // user1[2] is "pujkvBFU@kQKeYnabk.com"
    

提交回复
热议问题