Mongoose add multiple object to array if not exist based

前端 未结 1 1928
有刺的猬
有刺的猬 2020-11-30 15:13

How to add multiple objects to array based on key?

I need to add multiple objects in one query, check if each object key doesn\'t exist

相关标签:
1条回答
  • 2020-11-30 15:58

    You can try using bulkWrite operation in mongodb

    Suppose you have following payload to update

    const payload = [
      { key: "city", label: "CITY" }, { key: "gender", label: "GENDER" },
      { key: "city", label: "CITY1" }, { key: "city2", label: "CITY" }
    ]
    

    Query to update documents in bulk

    Model.bulkWrite(
      payload.map((data) => 
        ({
          updateOne: {
            filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } },
            update: { $push: { additional: data } }
          }
        })
      )
    })
    

    Which will send a request in bulk to update like this

    bulkWrite([
      { updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } },
      { updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } }
    ])
    
    0 讨论(0)
提交回复
热议问题