简体   繁体   中英

Projection of mongodb subdocument and get subdocument as class in c#

Hi. I have a Collection named "Level" with this class structure :

    public class Level 
    {
      [BsonId]
      public string Id {get; set;}
      public string Name { get; set; }
      public int Number { get; set; }
      public int TotalScore { get; set; }
      public int QuestionCount { get; set; }
      public IEnumerable<ConnectingQuestion> ConnectingQuestions { get; set; }
    }
    public class ConnectingQuestion 
    {
      [BsonId]
      public string Id { get; set; }
      public int QuestionNumber { get; set; }        
      public string Description { get; set; }       
      public string Type { get; set; }  
      public string Title { get; set; }
    }

and collection structure like this :

{ 
"_id" : "64e850f95322e01e88f131a2", 
"Name" : "First Level", 
"Number" : NumberInt(1), 
"TotalScore" : NumberInt(2690), 
"QuestionCount" : NumberInt(40), 
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fb43", 
        "QuestionNumber" : NumberInt(1), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title1", 
     },
     {
        "_id" : "5a130570738634297478fb76", 
        "QuestionNumber" : NumberInt(2), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title2", 
     },
     {
        "_id" : "5a130570738634297478fb23", 
        "QuestionNumber" : NumberInt(3), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title3", 
     }
    ]
}
{ 
"_id" : "59e850f95322e01e88f131c1", 
"Name" : "Second Level", 
"Number" : NumberInt(2), 
"TotalScore" : NumberInt(8000), 
"QuestionCount" : NumberInt(20), 
"ConnectingQuestions" : [
    {
        "_id" : "5a130570738634297478fa56", 
        "QuestionNumber" : NumberInt(1), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title1", 
     },
     {
        "_id" : "5a130570738634297478fb66", 
        "QuestionNumber" : NumberInt(2), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title2", 
     },
     {
        "_id" : "5a130570738634297478fe32", 
        "QuestionNumber" : NumberInt(3), 
        "Description" : "desc", 
        "Type" : "sc", 
        "Title" : "title3", 
     }
    ]
}

i need to write Query in c# that first select level with specified id and in selected level, select and return "ConnectingQuestion" subcollection with certain "QuestionNumber" in type of ConnectingQuestion class and not BsonDocument. A pseudo-query like this:

 ConnectingQuestion cq = MongoDB.Levels.find(level.id == "59e850f95322e01e88f131c1" && level.ConnectingQuestions.QuestionNumber == 2).Projection(level.ConnectingQuestions).SingleOrDefault();

Here are two possible solutions - there may be simpler ones...

Version 1: Using find() and project() only plus some BSON magic

var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var projection = Builders<Level>.Projection.ElemMatch(level => level.ConnectingQuestions, q => q.QuestionNumber == 2);
var bsonDocument = collection
    // filter out anything that we're not interested in
    .Find(level => level.Id == "59e850f95322e01e88f131c1")
    .Project(projection)
    .First();
// get first (single!) item from "ConnectingQuestions" array
bsonDocument = bsonDocument.GetElement("ConnectingQuestions").Value.AsBsonArray[0].AsBsonDocument;
// deserialize bsonDocument into ConnectingQuestions instance
ConnectingQuestion cq = BsonSerializer.Deserialize<ConnectingQuestion>(bsonDocument);

Version 2: Using the aggregation framework ( $filter needs MongoDB >= v3.2)

var collection = new MongoClient().GetDatabase("test").GetCollection<Level>("test");

var cq = collection.Aggregate()
    // filter out anything that we're not interested in
    .Match(level => level.Id == "59e850f95322e01e88f131c1")
    // filter the ConnectingQuestions array to only include the element with QuestionNumber == 2
    .Project<Level>("{ 'ConnectingQuestions': { $filter: { input: '$ConnectingQuestions', cond: { $eq: [ '$$this.QuestionNumber', 2 ] } } } }")
    // move the first (single!) item from "ConnectingQuestions" array to the document root level
    .ReplaceRoot(q => q.ConnectingQuestions.ElementAt(0))
    .FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM