Chapter 3 - quiz questions

Hello,

I am doing this exercise:
“In the sample_training.zips collection add a boolean field “capital?” to all documents pertaining to ALBANY NY, and NEW YORK, NY. The value of the field should be true for all ALBANY documents and false for all NEW YORK documents.”

My first attempt was this:
db.zips.updateMany({“city”:“ALBANY”, “state”:“NY”}, {"$set":{“capital?”:true}})

But I notice that this add “capital?” as an element of the “state” field. Example:

{
_id: ObjectId(“5c8eccc1caa187d17ca731db”),
city: ‘ALBANY’,
zip: ‘12202’,
loc: { y: 42.641314, x: 73.764071 },
pop: 11097,
state: ‘NY’,
‘capital?’: true
}

Then I tried the same sentence without the “?” character:

db.zips.updateMany({“city”:“ALBANY”, “state”:“NY”}, {"$set":{“capital”:true}})

This works, and add the field “capital”. Example:

{
_id: ObjectId(“5c8eccc1caa187d17ca731db”),
city: ‘ALBANY’,
zip: ‘12202’,
loc: { y: 42.641314, x: 73.764071 },
pop: 11097,
state: ‘NY’,
‘capital?’: true,
capital: true
}

But then I tried add others fields with symbols like “!” just for fun:

db.zips.updateMany({“city”:“ALBANY”, “state”:“NY”}, {"$set":{“test!”:true}})

And this add “test!” as an element of the field “capital” too, not as an field in the documents. Example:

{
_id: ObjectId(“5c8eccc1caa187d17ca731db”),
city: ‘ALBANY’,
zip: ‘12202’,
loc: { y: 42.641314, x: 73.764071 },
pop: 11097,
state: ‘NY’,
‘capital?’: true,
cap: true, ‘test!’: true
}

I wonder if adding symbols like “?” or “!” is against the name convention for fields, and that’s why I get elements instead of fields. Also, was the exercise intended to experiment this behavior? Because explicitly stated “capital?”.

Thank you!

notice the comma in between? these are two independent fields as you set them independently. you are creating all-new different fields. that is also why they are quoted. they are just mere strings. no special meaning.

in queries there are 2 symbols with special meanings, $, $$, and -, but only in places with special operators. otherwise, they can be used anywhere just as any other character enclosed in quotes to denote a “string” value, even in field names. and only $ needs special care if used at the beginning of the field name.

there is also a dot, ., in conjunction with $, to access sub-fields but again in special operations, such as {"$loc.y":{$gte: 42}}

I suggest you take time and study JSON structure along with Javascript objects as they are directly related to the query language. (MongoDB uses extended version, BSON)

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.