[英]MongoDb C# : get all matching sub-documents
Suppose I have the below Merchant document structure 假设我具有以下商家文档结构
Merchants 招商
[
{
"ID":"1",
"Name":"Merchant 1",
"Vendors":[
{
"ID":"1",
"Name":"Vendor 1",
"Currency":"GBP"
},
{
"ID":"2",
"Name":"Vendor 2",
"Currency":"EURO"
},
{
"ID":"3",
"Name":"Vendor 3",
"Currency":"GBP"
}
]
},
{
"ID":"2",
"Name":"Merchant 2",
"Vendors":[
{
"ID":"4",
"Name":"Vendor 4",
"Currency":"GBP"
},
{
"ID":"5",
"Name":"Vendor 5",
"Currency":"EURO"
},
{
"ID":"6",
"Name":"Vendor 6",
"Currency":"GBP"
}
]
}
]
Now I would like to get merchant whose Id is 2 and all it's vendors whose Currency is GBP. 现在,我想获得ID为2的商人以及货币为GBP的所有商人。
Output would be 输出将是
{
"ID":"2",
"Name":"Merchant 2",
"Vendors":[
{
"ID":"4",
"Name":"Vendor 4",
"Currency":"GBP"
},
{
"ID":"6",
"Name":"Vendor 6",
"Currency":"GBP"
}
]
}
How could I do this using .Find method in mongodb & C#? 如何在mongodb和C#中使用.Find方法执行此操作?
I am thinking about aggregation framework but I couldn't just make it to work. 我正在考虑聚合框架,但我不能仅仅使其起作用。
db.Merchants.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
"ID": "2"
}
},
// Stage 2
{
$project: {
ID: 1,
Name: 1,
Vendors: {
$filter: {
input: "$Vendors",
as: "vendor",
cond: {
$eq: ["$$vendor.Currency", "GBP"]
}
}
}
}
},
]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.