2

Query:

db.getCollection('parents').insertMany(
    [{
        'name': 'Mark',
        'children': 'No Childs'
    },{
        'name': 'Carl',
        'children': '2'
    }], {
      'ordered': true,
    }
)

I'm using mongoose as ORM

Can someone please suggest if we have any options like unique: true? I want the content to be checked not the _id since it will never be duplicate

Note: I've tried findOneAndUpdate using upsert: true, but here I've to insert multiple docs at the same time

2 Answers 2

5

As per the documentation if you have an unique index on a field (in your case name) and you are trying to insert multiple documents with insertMany you will get an exception the moment an error occurs:

Inserting a duplicate value for any key that is part of a unique index, such as _id, throws an exception.

However if you set 'ordered': false the execution of the insertMany would not stop and you would have those documents which do not conflict with the unique index inserted:

With ordered to false, the insert operation would continue with any remaining documents.

So setup an unique index on the name field and when you do insertMany only those records which violate that index would be skipped.

Sign up to request clarification or add additional context in comments.

Comments

3

While defining the model schema you can specify which field is unique for example:

var userSchema = new mongoose.Schema(
{ 
  FieldName:{ 
             type: String, 
             unique:true 
            }
})
var UserModel = mongoose.Model('User',userSchema);

If you want just to add index there is

schema.index({FieldName1: 1, FieldName2: 1}, {unique: true});

Or more details can be found here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.