How to change the data type in mongodb shell?

In the below query, i created “capital?” for boolean purpose, but instead of typing true i just typed “true” as string.

MongoDB Enterprise atlas-7aawne-shard-0:PRIMARY> db.zips.updateMany({“state”:“NY”,“city”:“ALBANY”},{"$set":{“capital?”:“true”}})
{ “acknowledged” : true, “matchedCount” : 7, “modifiedCount” : 7 }

MongoDB Enterprise atlas-7aawne-shard-0:PRIMARY> db.zips.find({“state”:“NY”,“city”:“NEW YORK”}).count()
40
MongoDB Enterprise atlas-7aawne-shard-0:PRIMARY> db.zips.updateMany({“state”:“NY”,“city”:“NEW YORK”},{"$set":{“capital?”:“false”}})
{ “acknowledged” : true, “matchedCount” : 40, “modifiedCount” : 40 }

Now I just unset the field by using “$unset”:

MongoDB Enterprise atlas-7aawne-shard-0:PRIMARY> db.zips.find({“capital?”:“true”}).count()
7
MongoDB Enterprise atlas-7aawne-shard-0:PRIMARY> db.zips.updateMany({“state”:“NY”,“city”:“ALBANY”},{"$unset":{“capital?”:""}})
{ “acknowledged” : true, “matchedCount” : 7, “modifiedCount” : 7 }

Q1) Is there any other easy method to delete a particular field ?
Q2) Is there anyway to change the data type of particular value in mongodb shell?
Q3) How can I retrieve the deleted documents which has “state”:“NY”, “city”:“NEW YORK”?

No. It cannot be easier than one line.

You use $set just like you did. For example, you could do

db.zips.updateMany({"capital?":"false"},{"$set":{"capital?": false }})

to change the field capital? from the string "false" to boolean false.

What’s deleted is deleted forever. What’s $unset is also gone forever. If you have backups you may retrieve from backups.

Thanks @steevej-1495 . I didn’t have any back up, that’s why I got wrong numeric value for every lab question, even though I wrote my query correct. :worried:

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