Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: can I compare if value in one field is contained in another field

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'}}.
like image 839
user1790300 Avatar asked Dec 10 '20 06:12

user1790300


1 Answers

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

like image 194
s7vr Avatar answered Oct 27 '22 00:10

s7vr