How to get all embedded document values ​​using official C # driver for MongoDB?

Given the following classes and an example document, how to get an AnswerChoice document from a collection of questions, where the _id in AnswerChoice is "4d6d336ae0f84c23bc1fae00" using the official C # driver. Thank.

public class Question
{
     [BsonId]
     public ObjectId QuestionId
     {get;set;}

     public string Question
     {get;set;}

     public List<AnswerChoice> AnswerChoices
     {get;set;}
}

public class AnswerChoice
{
     [BsonId]
     public ObjectId AnswerChoiceId
     {get;set;}

     public string Answer
     {get;set;}

     public int Order
     {get;set;}

}

// Example document

{
  "_id": "4d6d3369e0f84c23bc1facf7",
  "Question": "Question 1",
  "AnswerChoices": [
    {
      "_id": "4d6d3369e0f84c23bc1facf2",
      "Answer": "Answer Choice A",
      "Order": 1
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf3",
      "Answer": "Answer Choice B",
      "Order": 2
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf4",
      "Answer": "Answer Choice C",
      "Order": 3
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf5",
      "Answer": "Answer Choice D",
      "Order": 4
    },
    {
      "_id": "4d6d3369e0f84c23bc1facf6",
      "Answer": "Answer Choice E",
      "Order": 5
    }
}

// Code to retrieve a question that has an AnswerChoice with _id from "4d6d336ae0f84c23bc1fae00"

List<Question> list = new List<Question>();
MongoServer _server = MongoServer.Create("mongodb://localhost");
MongoDatabase _database = _server.GetDatabase("test");
var query = Query.And(Query.EQ("AnswerChoices._id", new ObjectId("4d6d336ae0f84c23bc1fae00")));
MongoCollection<Question> collection = _database.GetCollection<Question>("Question");
MongoCursor<Question> cursor = collection.Find(query);

foreach (var q in cursor)
{
    list.Add(q);
}

// How to get an AnswerChoice object using _id "4d6d336ae0f84c23bc1fae00" ?????

+3
source share
2 answers

You must download the question (as in the code above) and use linq or foreach to get the response element with the specified _id. The code will look like this:

List<Question> list = new List<Question>();
MongoServer _server = MongoServer.Create("mongodb://localhost");
MongoDatabase _database = _server.GetDatabase("test");
var query = Query.And(Query.EQ("AnswerChoices._id", new ObjectId("4d6d336ae0f84c23bc1fae00")));
MongoCollection<Question> collection = _database.GetCollection<Question>("Question");
MongoCursor<Question> cursor = collection.Find(query);

var id = new ObjectId("4d6d336ae0f84c23bc1fae00");
foreach (var q in cursor)
{
    var answerChoice = q.AnswerChoices.Single(x=> x.AnswerChoiceId == id);
    list.Add(q);
}

Find FindOne ( , , _id).

+4
+4

Source: https://habr.com/ru/post/1795812/


All Articles