Ajeetkumar
Ajeetkumar

Reputation: 1329

mongodb not updating all the documents

I have documents {name:"ajeetkumar",age:26} and {age:26,name:"ajeetkumar"} stored in collection sample.

I want to update the age field and i use command db.sample.update({name:"ajeetkumar"},{$set:{age:28}})

It only updates the first document where name is the first field. Why? How to update all the records given a field. Is order of fields affecting the update?

Upvotes: 4

Views: 2423

Answers (2)

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

{name:"ajeetkumar",age:26} and {age:26,name:"Ajeetkumar"}

db.sample.update({name:"ajeetkumar"},{$set:{age:28}})

In the second document name is starting with uppercase A so you should use regex in this one. Plus you have to use multi option. This one will work well for you:

db.sample.update({name: /^ajeetkumar/i},{$set:{age:28}}, {multi: true})

Upvotes: 1

Eddie Martinez
Eddie Martinez

Reputation: 13910

by default it only updates one you have to set the multi option, more info

try this:

db.sample.update({name:"ajeetkumar"},{$set:{age:28}}, false, true)

Also the query is case sensitive so in your case it still would not update the second one.

{name:"ajeetkumar",age:26} and {age:26,name:"Ajeetkumar"}

In the second document name is starting with uppercase A. Might want to look into regex matching

Upvotes: 2

Related Questions