Suppose I have a collection a called collection_a
that contains a lookup to a collection b called collection_b
. If the collection contains a field called primary_color
and the lookup contains a field called available_colors
. How can I compare primary_color
to available_colors
to see if the current value for primary_color
is contained in the available_colors
list?
I tried the following but it did not work in a aggregate match,
{'primary_color': {'$in': '$collection_b.available_colors'}}.
It is not possible to refer another collection in $match
stage.
You have to use $lookup
or populate in mongoose.
db.collectiona.aggregate([
{"$lookup":{
"from":collectionb,
"localField":"primary_color",
"foreignField":"available_colors",
"as":"matches"
}},
{"$match":{"matches.0":{"$exists":true}}}
])
https://mongoplayground.net/p/bkQzZcrP0aJ
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