Reorder array of elements using MongoDB

I have an array of objects that I would like to insert into a MongoDB collection, however I would like to check if each item is already in the collection. If it doesn't exist, insert it if it exists, and don't insert it.

After some Googling, it looks like I am best using the update method with the upsert property set to true.

It seems to be fine if I pass one element to it, and also if I iterate over my array and insert the elements one at a time, however I am not sure if this is the right way to do it, or if it is most efficient. Here's what I am doing at the moment:

var data = [{}, {}, ... {}];

for (var i = 0; i < data.length; i++) {

  var item = data[i];

  collection.update(
    {userId: item.id},
    {$setOnInsert: item},
    {upsert: true},
    function(err, result) {

      if (err) {
        // Handle errors here
      }

  });

}

      

Iterating over my array and inserting them one by one is the most efficient way to do this, or is there a better way?

+3


source to share


1 answer


I see two options here, depending on your specific needs:

  • If you need to insert or update , use upsert query . In this case, if the object is already present, you will update it - if your document has some content, it means that you may overwrite the previous value of some fields. As you can see, using it $setOnInsert

    will mitigate this problem.
  • If you need to insert or ignore , add a unique index to the appropriate fields and let the insert fail with the duplicate key. Since you have multiple documents to insert, you can send them all to an array using unordered insert (i.e.: setting the parameter ordered

    to false

    ), so MongoDB will continue to insert the remaining documents in case of an error with one of them.


As with performances, MongoDB's second option will use an index to find a possible duplicate. So chances are good, it will be better.

+2


source







All Articles