[英]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
.假设我有一个名为collection_a
的集合,其中包含对名为collection_b
的集合 b 的查找。 If the collection contains a field called primary_color
and the lookup contains a field called available_colors
.如果集合包含一个名为primary_color
的字段,并且查找包含一个名为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?如何比较primary_color
和available_colors
以查看primary_color
的当前值是否包含在available_colors
列表中?
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.在$match
阶段无法引用另一个集合。
You have to use $lookup
or populate in mongoose.您必须使用$lookup
或填充 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 https://mongoplayground.net/p/bkQzZcrP0aJ
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.