简体   繁体   中英

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'}}.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM