[英]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) 我想用C#返回此信息:(所有文档中只有子文档(国家/地区为美国))
{
"_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"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.