Reputation: 526
I have a collection like this:
{
side1:"apple",
side2:"peach",
a1:[
{_id:"apple", info:"test"},
{_id:"orange", info:"test"},
],
a2:[{_id:"banana", info:"test"},
{_id:"peach", info:"test"},
{_id:"apple", info:"test"}]
}
I'm looking for a way to list only subdocuments of a1
and a2
which their _id
values are respectively equal to side1
and side2
.
I mean the result should be the following :
{
side1:"apple",
side2:"peach",
a1:{_id:"apple", info:"test"},
a2:{_id:"peach", info:"test"}
}
I googled a lot and I have read about $filter
, $elemMatch
and $where
but I could not use them to solve my problem.
Upvotes: 2
Views: 691
Reputation: 35328
An aggregation pipeline like this
db.getCollection('yourColl').aggregate([
{
$project: {
_id: 0,
side1: 1,
side2: 2,
a1: {
$filter: {
input: "$a1",
as: "e",
cond: {
$eq: ["$$e._id", "$side1" ]
}
}
},
a2: {
$filter: {
input: "$a2",
as: "e",
cond: {
$eq: ["$$e._id", "$side2" ]
}
}
}
}
}
])
would have this output for your sample data
{
"side1" : "apple",
"side2" : "peach",
"a1" : [
{
"_id" : "apple",
"info" : "test"
}
],
"a2" : [
{
"_id" : "peach",
"info" : "test"
}
]
}
Upvotes: 2