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.
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#?
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"]
}
}
}
}
},
]
);
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.