Posts

Showing posts with the label BSON

MongoDB tip: cursor.map

This is just a quick example of how we can use cursor.map to change the shape of the array. //push all the _id we found into an array, but the problem we have right now is how it's stored as array of documents while we are only interested in the value. var updateArray = db.getSiblingDB("equipment").needProcessedEquip.find({}, {_id: 1}).toArray(); updateArray; [     {         "_id" : "5680e9b8-6ffe-41bb-a035-e255ede87b8e"     },     {         "_id" : "08b08206-f2a7-49b8-bf7a-b72a6494e556"     },     {         "_id" : "17e49c0d-0892-4f4b-a0c5-effaaf07a058"     },     {         "_id" : "1b1756ce-63fe-4b9e-baf3-e2f418feb3d7"     },     {         "_id" : "e31a02f6-e217-4172-bcf5-684ab40321de"     },     {         "_id" : "01f6fcab-4123-44aa-a...

MongoDB tip, identify and convert type of a specific field

Image
I found this post when I encountered some type issue and the better solution seems to be to convert the type in place. So I just did a quick experiment myself to make sure it works properly. to set up this experiment, first run db.testConvert.insert({typeField:NumberLong(1)}); db.testConvert.insert({typeField:NumberInt(1)}); db.testConvert.insert({typeField:1}); We verify now typeField has contain all three types, Int64, Int32, and Double Referencing from BSON type documentation, we know that Double is 1. Then we run the following var bulk = db.testConvert.initializeUnorderedBulkOp(), count=0; db.testConvert.find({"typeField":{"$type":1}}).forEach(function(doc) {     bulk.find({"_id":doc._id}).updateOne({         "$set":{"tmpField":NumberLong(doc.typeField.valueOf())},         "$unset":{"typeField":1}     });     bulk.find({"_id": doc._id}).updateOne({ "$rename": { ...