MongoDB insert with unique index

Suppose I have a list of documents that I want to insert.

Documents are structured as follows

{
  url: string,
  visited: boolean
}

I have a unique index on the key url.

When I insert documents, if 1 duplicate is found, the whole operation is aborted.

Is there a way that I can still use batch insertion and it will insert all documents that are not duplicated?

As a workaround, I have to insert documents one by one, and I am afraid of the performance impact of the insertion overhead.

+4
source share
2 answers

, a, .getIndexes()

> db.collection.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.collection"
        },
        {
                "v" : 1,
                "unique" : true,
                "key" : {
                        "a" : 1
                },
                "name" : "a_1",
                "ns" : "test.collection"
        }
]

:

var docs = [ { 'a': 3  }, { 'a': 4 }, { 'a': 3 } ];

Bulk() API , , MongoDB , .

var docs = [{a: 3}, {a: 4}, {a: 3}]
var bulk = db.collection.initializeUnorderedBulkOp();
for(var ind=0; ind<docs.length; ind++) { 
    bulk.insert(docs[ind]); 
}
bulk.execute();

, .

, bulk.execute() db.collection.find() :

{ "_id" : ObjectId("5629c5d1e6d6a6b8e38d013c"), "a" : 3 }
{ "_id" : ObjectId("5629c5d1e6d6a6b8e38d013d"), "a" : 4 }
+3

Source: https://habr.com/ru/post/1612872/


All Articles