简体   繁体   English

Mongodb:我可以比较一个字段中的值是否包含在另一个字段中

[英]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_coloravailable_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.

相关问题 为什么我可以在MongoDB中更新一个字段,而不更新另一个字段? (MEAN Stack) - Why can I update one field but not another in MongoDB? (MEAN Stack) mongodb 聚合:如何将分钟添加到日期字段然后进行比较 - mongodb aggregation: How can i add minutes to a date field and then compare it 如何在mongodb中用另一个覆盖模式的一个字段 - How to overwrite one field of a schema with another in mongodb MongoDB 根据另一个字段的值查询数组 - MongoDB Query array based on value of another field 如何通过使用 nodejs 在 mongodb 中指定其匹配字段之一来修改记录的字段 - How can i modify a field of a record by specifying one of its matching field in mongodb using nodejs 如何将非数组字段与 mongodb 中的数组进行比较? - How Do I compare non-array field with array in mongodb? 如何查询MongoDB中的引用字段? - How can I query on a referenced field in MongoDB? 如何使用 Mongoose 在给定另一个嵌套字段值的情况下更新嵌套字段? - How can I update a nested field given another nested field value with Mongoose? 按字段过滤,然后选择另一个字段mongodb - Filter by field and select another field mongodb 使用来自另一个字段的值进行推送的 UpdateOne MongoDB - UpdateOne MongoDB with push using value from another field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM