Dawn17
Dawn17

Reputation: 8297

Replacing a document in MongoDB when the imported document has a same id (mongoimport)

I am trying to mongoimport a jsonarray file to my MongoDB.

I used the command below for my previous import and has been successful:

mongoimport.exe --host <host> --db <db> --collection <collection> --type json --file <file> --jsonArray --authenticationDatabase admin --ssl --username <id> --password <pw>

This time I am trying to import another jsonarray that contains the same structured documents but some of them have same _ids as some documents that are already in the MongoDB.

enter image description here

This is the structure of a document.

I am concered because the _id field is not an ObjectId but just an integer that I manually labeled, so it would not consider new documents with the same _id (but with other modified fields) as the same object and will not overwrite it.

How can I overwrite the document that has the same _id as the imported documents (and of course add new documents that do not overlap with any of the documents in the DB)?

Thanks

Upvotes: 1

Views: 1026

Answers (1)

Dawn17
Dawn17

Reputation: 8297

I should have read the documentation more carefully.

With --mode upsert, mongoimport replaces existing documents in the database that match a document in the import file with the document from the import file. Documents that do not match an existing document in the database are inserted as usual. By default mongoimport matches documents based on the _id field. Use --upsert Fields to specify the fields to match against.

Upvotes: 1

Related Questions