简体   繁体   中英

Projecting only matched sub-documents along with original document fields mongodb C#

Suppose this is how my data looks:

{
"_id" : ObjectId("545dad3562fa028fb48832f0"),
"number" : "123456",
"persons" : [
        {
                "name" : "A",
                "country" : "US"
        },
        {
                "name" : "N",
                "country" : "Australia"
        },
        {
                "name" : "Z",
                "country" : "US"
        }

]
}
{
"_id" : ObjectId("545dad3562fa028fb48832f0"),
"number" : "123457",
"persons" : [
        {
                "name" : "Q",
                "country" : "India"
        },
        {
                "name" : "B",
                "country" : "Brazil"
        },
        {
                "name" : "U",
                "country" : "UK"
        }

]
}

I want to return this in C#:(All documents with only sub-documents where country is US)

{
"_id" : ObjectId("545dad3562fa028fb48832f0"),
"number" : "123456",
"persons" : [
        {
                "name" : "A",
                "country" : "US"
        },
        {
                "name" : "Z",
                "country" : "US"
        }

]
}

Currently I am able to get the documents containing the matched sub-documents but also with the non-relevant sub-documents. Query that I tried:

filter = Builders<BsonDocument>.Filter.Eq(c => c.number, "123456") & Builders<BsonDocument>.Filter.ElemMatch(c => c.persons, x => x.country == "US");
var result = client.GetDatabase(MyMongoDB).GetCollection<MyCollection>(CollectionName).Find<MyCollection>(filter);

you can do this with aggreggation like this :

db.collection.aggregate([
   {
      $match:{
         "persons.country":"US"
      }
   },
   {
      $redact:{
         $cond:{
            if:{
               $or:[
                  {
                     $eq:[
                        "$country",
                        "US"
                     ]
                  },
                  {
                     $or:"$number"
                  }
               ]
            },
            then:"$$DESCEND",
            else:"$$PRUNE"
         }
      }
   }
])

this will output :

{
   "_id":ObjectId("545dad3562fa028fb48832f0"),
   "number":"123456",
   "persons":[
      {
         "name":"A",
         "country":"US"
      },
      {
         "name":"Z",
         "country":"US"
      }
   ]
}

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