Is there a way to insert or update/replace multiple documents in MongoDB with a single query?
Assume the following collection:
[ {_id: 1, text: "something"}, {_id: 4, text: "baz"} ] Now I would like to add multiple documents of which some might already be in the collection. If the documents are already in the collection, I would like to update/replace them. For example, I would like to insert the following documents:
[ {_id:1, text: "something else"}, {_id:2, text: "foo"}, {_id:3, text: "bar"} ] The query should insert the documents with _id 2 and 3. It should also update/replace the document with _id 1. After the process, the collection should look as follows:
[ {_id:1, text: "something else"}, {_id:2, text: "foo"}, {_id:3, text: "bar"}, {_id:4, text: "baz"} ] One approach might be to use insertMany:
db.collection.insertMany( [ {...}, {...}, {...} ], { ordered: false, } ) If duplicates occur, that query will emit a writeErrors containing an array of objects containing the indexes of the documents that failed to insert. I could go through them and update them instead.
But that process is cumbersome. Is there a way to insert or update/replace many documents in one query?