简体   繁体   English

基于另一个集合更新集合的字段 - MongoDB

[英]Update field of a collection based on another collection - MongoDB

I have two collections The structure of collection A is我有两个 collections 集合 A 的结构是

{
     id:
     product:
}

The structure of collection B is集合 B 的结构是

{
     id:
     product:
     status:
}

I want to update collection B like if a product exists in collection A, then it will set status 1 to the corresponding document of collection B.我想更新集合 B,就像集合 A 中存在产品一样,它会将状态 1 设置为集合 B 的相应文档。

The SQL syntax would be like SQL 语法就像

UPDATE B SET B.STATUS = 1 WHERE B.PRODUCT IN (SELECT PRODUCT FROM A);

I just need to do the same in MongoDB.我只需要在 MongoDB 中做同样的事情。 Thanks in advance.提前致谢。

In MongoDB 4.2 you can do this with aggregation.在 MongoDB 4.2 中,您可以通过聚合来执行此操作。

  • Aggregate collection A集合A
  • $lookup from collection B with local and foreign fields both set to "product"集合 B 中的$lookup ,本地和外国字段均设置为“产品”
  • $unwind the array returned from lookup $unwind从查找返回的数组
  • $replaceRoot to make the looked up document to root $replaceRoot将查找到的文档设为 root
  • $project status: {$literal:1} $项目status: {$literal:1}
  • $merge with collection B $merge与集合 B

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDB:根据另一个集合更新一个集合 - MongoDB: update a collection based on another collection 如何根据MongoDB中的另一个集合更新集合? - How to update a collection based on another collection in MongoDB? 基于MongoDB中另一个集合中的数据更新集合 - Update collection based on data in another collection in MongoDB 如何基于MongoDB中的另一个集合嵌入字段值更新嵌入集合字段的数组? - How to update array of embedded collection field based on another collection embedded field value in MongoDB? 根据另一个集合字段值设置一个 MongoDB 集合字段值 - Set the a MongoDB collection field value based on another collection field value 基于另一个集合上的字段对文档进行分组 Mongodb - Group documents based on field on another collection Mongodb 如何使用另一个集合中的字段值更新Mongodb集合中的文档 - How to update document in Mongodb collection with a field value from another collection 根据是否存在另一个集合获取 MongoDB 集合字段值 - Get the MongoDB collection field value based on if another collection exists or not MongoDB 用另一个集合中的另一个字段更新字段 - MongoDB update field with another field from another collection mongodb 更新集合中的字段同时自动生成另一个字段 - Mongodb update field in collection and at the same time generated automaticly another field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM