Mongodb – Inserting many documents in collection, but only unique elements, based on specific field

mongodbnode.jsnosql

I cannot seem to find an answer on this anywhere. I need the following:

Given an array of objects with the structure:

    {
       link: 'some-link',
       rating: 25,
       otherFields: '..',
       ...
    }

I want to insert them into my collection. So I would just do insertMany… But I only want to insert those elements of the array that are unique, meaning that I do not want to insert objects with the field "link" being something that is already in my collection.

Meaning if my collection has the following documents:

    {
      _id: 'aldnsajsndasd',
      link: 'bob',
      rating: 34,
    }
    {
       _id: 'annn',
       link: 'ann',
       rating: 45
    }

And I do the "update/insert" with the following array:

    [{
      link: 'joe', 
      rating: 10
    },{
      link: 'ann',
      rating: 45
    }, {
      link: 'bob',
      rating: 34
    }, {
      link: 'frank',
      rating: 100
    }]

Only documents:

    {
      link: 'frank',
      rating: 100
    }
    { 
      link: 'joe',
      rating: 10
    }

Would be inserted in my collection

Best Answer

First add an unique constraint on field link.

db.collection.createIndex({"link": 1}, {unique: true})

And then without using insertMany, insert each document of the list using javscript functions.

Lastly remove the index(unique constraint) we no longer need.

db.collection.dropIndex("link_1") // or your index name
Related Question