arraysmongodbmongodb-querynosqldocument-oriented-db

How to do a bulk update to a Mongo DB array of objects with json matched by id


I need to update the MongoDB field with the array of objects which has id needs to be updated with same id in the JSON object

if I have some thing like this in MongoDB

{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          name: "ABC"
        },
        {
          id : 123,
          name: "ABCD"
        }
    ]
}

And I have the JSON data like this to be inserted in Mongo

{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          author: "ccc"
        },
        {
          id : 123,
          author: "dddd"
        }
    ]
}

After update I need the final data like this in Mongo collection

{
    _id: "adqeer32423twefds",
    books : [
        {
          id : 111,
          name: "ABC",
          author: "ccc"
        },
        {
          id : 123,
          name: "ABCD",
          author: "dddd"
        }
    ]
}

Solution

  • You can use positional update to do it one by one, and batch those updates using bulkWrite.

    const data = [
      { _id: 'id1', books: [{ id: 'id1_1', author: 'author1_1' }, /* ... */] },
      /* ... */
    ];
    
    const bulk = [];
    for (const { _id, books } of data) {
      for (const { id, author } of books) {
        bulk.push({
          updateOne: {
            filter: { _id, 'books.id': id },
            update: { $set: { 'books.$.author': author } }
          }
        });
      }
    }
    
    // Check if bulk is not empty - it will throw otherwise.
    if (bulk.length > 0) db.collection.bulkWrite(bulk);