Mongodb更新多个文档,如果不存在则插入

时间:2019-01-26 09:51:08

标签: mongodb insert-update

如果设置了upsert:true,则mongodb插入新文档(如果存在)。 我的以下查询对于单个文档工作正常。 唯一索引:-{fid:1,uniqueid:1,atype:1,ftype:1}

db.Notification.updateMany(
  {fid : 103,uniqueid:1001,atype:1,ftype:6}
  ,{ $set: { epoch: 1548484978658,actionbyuserid: 110, title: 'Good Morning To All'}}
  ,{upsert:true}
);

但是在执行以下查询时,它不会为不匹配的文档插入新文档;

db.Notification.updateMany(
 {fid : {$in:[101,102,103]},uniqueid:1001,atype:1,ftype:6}
  ,{ $set: { epoch: 1548484978658,actionbyuserid: 110, title: 'Good Morning To All'}}
,{upsert:true}
)

还有其他检查和插入未找到的文档吗?

1 个答案:

答案 0 :(得分:2)

您可以使用bulkWrite操作

您要使用

更新的数组
const array = [101, 102, 103]

查询批量更新

Model.bulkWrite(
  array.map((val) => 
    ({
      updateOne: {
        filter: { _id: val, uniqueid: 1001, atype: 1, ftype: 6 },
        update: { $set: { epoch: 1548484978658, actionbyuserid: 110, title: 'Good Morning To All'} },
        upsert: true
      }
    })
  )
})