从一个 mongo 集合中删除与另一集合中匹配的文档

Mic*_*zda 5 mongodb

这可能是一个菜鸟问题,但是,如何(有效地)从一个 mongodb 集合中删除与另一集合中找到的文档匹配的所有文档?例如,使用 mongo shell,我们可以执行以下操作:

   db.getCollection('coll1').find({}).forEach( function(doc) {
     db.getCollection('coll2').remove( { name: doc.name, value: doc.value } );
   })
Run Code Online (Sandbox Code Playgroud)

小智 0

我建议使用带有删除的 $in 来完成此操作,方法是在带有删除的 $in 数组中传递名称或 Id 的数组。

 db.getCollection('coll1').find({}).forEach( function(doc) {
   
   // create idsArray from the doc data and pass same in $in
   
     db.getCollection('coll2').remove({ id: { $in: idsArray });
   })
Run Code Online (Sandbox Code Playgroud)

我希望它会有所帮助。:)