user1112259
user1112259

Reputation:

Why mongodb only updates the first matching document in the collection?

Consider a collection student contains the following documents.

{name:”Nithin”,age:23} 

{name:”Nithin”,age:25} 

{name:”Nithin”,age:28} 

{name:”Nithin”,age:12} 

I want to update all the documents whose name is “Nithin” as age=60. If we execute the following query it will only update the first document.

db.student.update({name:”Nithin”},{age:60})

For update all the documents I have to use the query

db.student.update({name:”Nithin”},{age:60},false,true) 

or 

db.student.update({name:”Nithin”},{age:60},multi:true)

What is the reason by default mongodb not updating all the documents by executing db.student.update({name:”Nithin”},{age:60}) ? What is the motivation for creating separate queries for updating all the documents? Is it improving the performance?

Upvotes: 0

Views: 912

Answers (3)

Dek Dekku
Dek Dekku

Reputation: 1461

I suppose part of the reason might be to avoid people coming from the SQL world to think about multi-document updates as isolated transactions.

In fact, during a long update MongoDB will periodically yield control to other queries which can potentially modify the same dataset.

So, by explicitly setting multi=true you are somewhat acknowledging this fact (well, not really, but I guess that's the spirit...)

Upvotes: 0

MervS
MervS

Reputation: 5902

This may not really be the reason but I find the additional multi parameter as a safeguard to prevent accidental update of multiple records when one intends to update a single document only, something like accidentally performing UPDATE...SET on SQL without specifying additional constraints.

Again this is just an assumption but may not really be the case.

Upvotes: 1

Ewan
Ewan

Reputation: 15058

Originally, in the early early days of MongoDB (pre 1.1) it was not possible to update multiple documents. This was a feature added around 1.1.3.

You can see it in the release notes, New Feature 268.

I'm guessing this was not enabled by default for backwards compatibility with previous versions.

Upvotes: 2

Related Questions