Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

way to update multiple documents with different values

Tags:

I have the following documents:

[{   "_id":1,   "name":"john",   "position":1 },  {"_id":2,   "name":"bob",   "position":2 },  {"_id":3,   "name":"tom",   "position":3 }] 

In the UI a user can change position of items(eg moving Bob to first position, john gets position 2, tom - position 3). Is there any way to update all positions in all documents at once?

like image 364
Linkorn Avatar asked Jun 20 '13 06:06

Linkorn


People also ask

How do you update multiple documents with different values?

You can not update two documents at once with a MongoDB query. You will always have to do that in two queries. You can of course set a value of a field to the same value, or increment with the same number, but you can not do two distinct updates in MongoDB with the same query.

Which of these operator is used to set the value of a field if an update results in an insert of a document has no effect on update operations that modify existing documents?

$setOnInsert This operator is used to set the value of a field if an update results in an insert of a document.

How do you update an entire document?

Update all fields in a documentPress Ctrl + A. Press F9. If your document has tables with fields or formulas, you might need to select each table separately and press F9.


2 Answers

You can not update two documents at once with a MongoDB query. You will always have to do that in two queries. You can of course set a value of a field to the same value, or increment with the same number, but you can not do two distinct updates in MongoDB with the same query.

like image 165
Derick Avatar answered Oct 21 '22 22:10

Derick


You can use db.collection.bulkWrite() to perform multiple operations in bulk. It has been available since 3.2.

It is possible to perform operations out of order to increase performance.

like image 35
Morozov Avatar answered Oct 21 '22 21:10

Morozov