Updating Many documents using conditional (quizz 3)

My question is about the quizz in chapter 3, in witch we should add a new field (capital?). I had tried to update both (New York and Albany) at the same time but no metter what i did in my query my shell kept telling me that I was missing a part (osome times a : , some times a { ). Some times I also have a bad output .

Could someone help me (could be with as similar exemple so we do not post the awnser here) . I just wanted to find a way to optimise my query.

The uery that not work:
db.zips.updateMany({$and:[{$or:[{“city”:“NEW YORK”}, {“city”:“ALBANY”}]}, {“state”: “NY”}]},{$set:{“capital?”:{$eq:{“city”:“ALBANY”}}}})

I also tryed to use this syntax (that did not work) : "Conditional" object update - #2 by slava

Thank you

I did this in two separate update calls. One updateMany() that sets “capital?” to “true” for documents matching { “state”: “NY”, “city”, “ALBANY” }, and another updateMany() that sets “capital?” to “false” for documents matching { “state”: “NY”, “city”, “NEW YORK” }. If there is a way to do this in one updateMany() call, I don’t think we’ve been taught how to do it at this point of the course.

The syntax provided by @slava should work. But it could be simply with just the $eq like you did but with some corrections.

Perhaps you missed the [ ] that enclosed the { "$set" : … }.

Another thing is tat the syntax for $eq when used as an update expression is { "$eq" : [ Value_1 , Value_2 ] }.

Finally, when referencing the value of field as one of the Value_n in your expression you need to prefix it with $ to indicate that you want the field value rather than the field name. When you specify "city" in your expression, it means the string value city but in your case you want to refer to the value of the field city so it has to be "$city".

If I try to add the "$"to city it gives me an error. I’m not sure why.

Because it is

rather than

Brackets rather than braces, because in this context $eq takes an array rather than an object.

The query

$or : [ { city : "NEW YORK" } , { city : "ALBANY" } ]

can be also written as

"city" : { "$in" : [ "NEW YORK" , "ALBANY" } }

Thank you @steevej your solution worked. :slight_smile:

1 Like