Let's say I have a document like bellow
{
fieldA : [
{
_id : 1,
value : 1,
},
{
_id : 2
value : 2,
},
{
_id : 3,
value : 3,
},
],
fieldB : [
{
_id : 2
},
{
_id : 3
},
{
_id : 4
},
],
}
I want to filter which _id in fieldB has in fieldA and take value in fieldA, add to new field name fieldC
Expected output
fieldC : [
{
_id : 2,
value : 2,
},
{
_id : 3,
value : 3,
},
]
I tried using $filter in $addFields but it returned an empty array
{
$addFields : {
fieldC : {
$filter : {
input : "$fieldB",
cond : {
$in : ["$$this._id", "$fieldA._id"]
}
}
}
}
}
fieldC = []
From my understanding, your expected behaviour is actually a set intersection behaviour. You may simply "swap" your $filter to do a._id in b._id.
db.collection.aggregate([
{
"$addFields": {
"fieldC": {
"$filter": {
"input": "$fieldA",
"as": "a",
"cond": {
"$in": [
"$$a._id",
"$fieldB._id"
]
}
}
}
}
}
])
Here is the Mongo playground for your reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With