仅投影匹配的子文档以及原始文档字段mongodb C#

时间:2016-11-30 12:43:20

标签: c# mongodb

假设这是我的数据的外观:

{
"_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"
        }

]
}

我想在C#中返回:(所有仅包含国家为美国的子文档的文档)

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

]
}

目前,我可以获取包含匹配的子文档的文档,但也可以获取不相关的子文档。 查询我尝试过:

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);

1 个答案:

答案 0 :(得分:0)

你可以用这样的聚合来做到这一点:

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

这将输出:

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