Reputation: 15685
Let's say I have the following two JSONs, and I'd like to import them to the same collection without merging or updating the existing documents. Is there a way, to ignore the existing _id keys during import and end up with a single collection containing all the 6 documents of the example below?
The old _id properties have no relevance whatsoever. I could rename/remove them from the source files, I'm just curious if there is a way to do this during import.
coll1.json:
{"_id":1,"a":1}
{"_id":2,"a":2}
{"_id":3,"a":3}
and
coll2.json:
{"_id":1,"a":4}
{"_id":2,"a":5}
{"_id":3,"a":6}
If I simply import them, with mongoimport --db imp --collection imp --file coll2.json
I'm getting E11000 duplicate key error.
Upvotes: 0
Views: 3277
Reputation: 1525
If you want to overwrite the document import by using following command
mongoimport --db imp --collection imp --mode upsert --file coll2.json
In mongodb _id field is by default unique so you cant have _id with same value like you had in your case
coll1.json:
{"_id":1,"a":1} // _id is same as document below
{"_id":2,"a":2}
{"_id":3,"a":3}
coll2.json:
{"_id":1,"a":4} // {"_id":1,"a":1}
{"_id":2,"a":5}
{"_id":3,"a":6}
What you can do in this case is Change the name of key from _id to id which will allow you to have more then one document with same value of id.
coll1.json:
{"idField":1,"a":1}
{"idField":2,"a":2}
{"idField":3,"a":3}
coll2.json:
{"idField":1,"a":4}
{"idField":2,"a":5}
{"idField":3,"a":6}
Upvotes: 2