Mongo - How to update multiple documents with different value in single query?

后端 未结 1 606
误落风尘
误落风尘 2020-12-06 13:41

I want to write a query for updating multiple documents in a single query, Please suggest me possible ways.

Following is my mongo document.

[
    {
          


        
相关标签:
1条回答
  • 2020-12-06 14:17

    You basically need bulkWrite operation in mongodb

    const array = [
      {
        "_id" : ObjectId("5b0f0a2ca1f6633032c204cd"),
        "parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
        "name" : "ABC123",
        "color":"red"
        "userType": "admin"
      },
      {
        "_id" : ObjectId("5b0f0a2ca1f6633032c204ce"),
        "parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
        "name" : "DEF123",
        "color":"blue"
        "userType": "admin"
      },
      {
        "_id" : ObjectId("5b0f0a2ca1f6633032c204cf"),
        "parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
        "name" : "GHI123",
        "color":"green"
        "userType": "admin"
      },
      {
        "_id" : ObjectId("5b0f0a2ca1f6633032c204d0"),
        "parent_id" : ObjectId("5b0f09e1a1f6633032c204cc"),
        "name" : "XYZ123",
        "color":"rgb(14,256,12, 1)"
        "userType": "admin"
      }
    ]
    

    And the final query

    Model.bulkWrite(
      array.map((data) => 
        ({
          updateOne: {
            filter: { _id: data._id },
            update: { $set: data }
          }
        })
      )
    })
    
    0 讨论(0)
提交回复
热议问题