Chapter 3: Creating and Manipulating Documents (Using $set conditionally to update documents)

I’m really having a difficult time understanding the syntax. Manual does not help, people use different syntaxes on the pages I found through Google. To find some help, I took the MongoDB University course, but it is still confusing.

The question is:

Practice Question:

People often confuse NEW YORK City as the capital of New York state, when in
reality the capital of New York state is ALBANY.

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 solution:

db.zips.updateMany(
	{
		$and: [	{"city":{"$in":["ALBANY","NEW YORK"]}},{"state":"NY"} ]
	},
	{
		$set: {
			"capital?": { 
				$switch: {
					branches: [ 
						{ case: { $eq: [ "$city", "ALBANY" ] }, then: true },
						{ case: { $eq: [ "$city", "NEW YORK" ] }, then: false }
					],
					default: " "
				}
			}
		}
	}   
)

It set the field “capital?” for ALBANY and NEW YORK in NY. Nevertheless, it included the part " $switch … ". Result:

{
    _id: ObjectId("5c8eccc1caa187d17ca72fa3"),
    city: 'NEW YORK',
    zip: '10022',
    loc: { y: 40.757091, x: 73.965703 },
    pop: 31870,
    state: 'NY',
    'capital?': {
      '$switch': {
        branches: [
          { case: { '$eq': [Array] }, then: true },
          { case: { '$eq': [Array] }, then: false }
        ],
        default: ''
      }
    }
  }

I then tried $cond which is resulted in “MongoServerError: Unknown modifier: $cond. Expected a valid update modifier or pipeline-style update specified as an array”:

db.zips.updateMany(
	{
		$and: [	{"city":{"$in":["ALBANY","NEW YORK"]}},{"state":"NY"} ]
	},
	{
		$cond: {
			if: {
				$eq: ["city", "ALBANY"]
			},
			then: {
				$set: {
					"capital?": true
				}
			},
			else: {
				$set: {
					"capital?": false
				}
			}
		}
	}
)

Looking for help using $set conditionally to update the documents…

You can run the following script to get the desired results (considering it is a Basics course):

db.zips.updateMany({"city":"ALBANY"},{"$set": {"capital?":"True"}})

db.zips.updateMany({"city":"NEW YORK"},{"$set": {"capital?":"False"}})

The error message indicates that $cond is not a modifier. It is an expression, while $set is a modifier.

You only need to reorder your logic, using $set as the modifier and $cond as the expression. Also, not that since you want the value of field city rather than the string "city" you need to use $.

[ { $set: {
  "capital?" : { $cond : {
    if: { $eq: ["$city", "ALBANY"] } ,
    then : { true } ,
    else : { false }
  } }
} } ]

and since $eq:["$city", “ALBANY”] is an expression that return true false you may simplify the whole thing to:

[ { $set: {
  "capital?" : { $eq : [ "$city" , "ALBANY" ] }
} } ]

Note that

has 2 major bugs so it cannot really be marked as the solution. First, there are 14 cities named ALBANY that are not in the state of NY. The $and condition of @Serhat_Demirkol did not have this bug since the state:NY was tested correctly. The other bug is that the requirements ask for a boolean field. The values “True” and “False” are strings rather than a boolean.

The following is more appropriate.

db.zips.updateMany({"city":"ALBANY","state":"NY"},{"$set": {"capital?":true}})
db.zips.updateMany({"city":"NEW YORK","state":"NY"},{"$set": {"capital?":false}})
1 Like

Thank you for the response. Can you please make sure that this one city two states scenario is added to the example? Otherwise others may also make this mistake like I did, especially if someone hasn’t taken US geography classes growing up.

I am not in control of the course content. I am a simple user like you.

Personally, it is not about knowing

It is about respecting the requirements. It was clearly stated they were taking about ALBANY and NEW YORK in the NY state. I don’t feel adding anything else would help. I think you and others that fails to add state:NY to their query just learn an important lesson about requirements.

And sometimes requirements are a little bit fuzzy like in

vs

Above quotes from Chapter 4 IDE - Examples

To remove any fuzziness it should be:

the value of the field sector be equals to the string "Home Improvement Contractor - 100"

But we don’t get that in real life. We get fuzzy requirements, but state:NY was not fuzzy.

And yes, to really match the fuzzy requirements, you are right about:

Above quote from Chapter 5: Quiz 1

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