0

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

0

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
| improve this answer | |
  • I think the question is about link field, not the rating. – prasad_ May 20 at 2:02
  • oops! you're right. I'll edit it – Kyoo Sik Lee May 20 at 6:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.