仅投影匹配的子文档以及原始文档字段 mongodb C# [英] Projecting only matched sub-documents along with original document fields mongodb C#
本文介绍了仅投影匹配的子文档以及原始文档字段 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"
}
]
}
我想在 C# 中返回这个:(所有文档只有国家是美国的子文档)
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"
}
}
}
])
这将输出:
{
"_id":ObjectId("545dad3562fa028fb48832f0"),
"number":"123456",
"persons":[
{
"name":"A",
"country":"US"
},
{
"name":"Z",
"country":"US"
}
]
}
这篇关于仅投影匹配的子文档以及原始文档字段 mongodb C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文