简体   繁体   中英

Update field of a collection based on another collection - MongoDB

I have two collections The structure of collection A is

{
     id:
     product:
}

The structure of collection B is

{
     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.

The SQL syntax would be like

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

I just need to do the same in MongoDB. Thanks in advance.

In MongoDB 4.2 you can do this with aggregation.

  • Aggregate collection A
  • $lookup from collection B with local and foreign fields both set to "product"
  • $unwind the array returned from lookup
  • $replaceRoot to make the looked up document to root
  • $project status: {$literal:1}
  • $merge with collection B

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