Gandalf The Gray
Gandalf The Gray

Reputation: 77

Mongodb add multi documents if one field doesnt exist

I have some documents that i want to add to my collection.

I want to add all of the objects in the array in a single action and when I have a something that exists I want to replace it.

{"a":0, "b":0, "myKey": "aaaaaa"}
{"a":0, "b":0, "myKey": "hhhhhh"}
{"a":0, "b":0, "myKey": "oooooo"}
{"a":0, "b":0, "myKey": "mmmmmm"}
{"a":0, "b":0, "myKey": "eeeeee"}

My collection looks like this when myKey is the unique key of the object:

Those are the documents that I want to add to my collection:

[
  {"a":1, "b":2, "myKey": "aaaaaa"},
  {"a":2, "b":3, "myKey": "bbbbbb"},
  {"a":3, "b":4, "myKey": "cccccc"},
  {"a":4, "b":5, "myKey": "dddddd"},
  {"a":6, "b":7, "myKey": "eeeeee"}
] 

I want my collection to look like this

{"a":1, "b":2, "myKey": "aaaaaa"}
{"a":0, "b":0, "myKey": "hhhhhh"}
{"a":0, "b":0, "myKey": "oooooo"}
{"a":0, "b":0, "myKey": "mmmmmm"}
{"a":6, "b":7, "myKey": "eeeeee"}
{"a":2, "b":3, "myKey": "bbbbbb"}
{"a":3, "b":4, "myKey": "cccccc"}
{"a":4, "b":5, "myKey": "dddddd"}

Is there any way to do that without sending many update actions?

Upvotes: 2

Views: 36

Answers (1)

chridam
chridam

Reputation: 103435

You can use bulkWrite for this operation as follows:

const array = [
  {"a":1, "b":2, "myKey": "aaaaaa"},
  {"a":2, "b":3, "myKey": "bbbbbb"},
  {"a":3, "b":4, "myKey": "cccccc"},
  {"a":4, "b":5, "myKey": "dddddd"},
  {"a":6, "b":7, "myKey": "eeeeee"}
];
let ops = [];
array.forEach(({ a, b, myKey }) => {
    ops.push({
       "updateOne": { 
           "filter": { myKey },
           "update": { "$set": { a, b, myKey } },
           "upsert": true   
       }            
    })           
});

db.collection.bulkWrite(ops);

Upvotes: 1

Related Questions