Posts

Showing posts from May, 2019

MongoDB Tips - Using _id to determine when the object was inserted

MongoDB objectid conversion to timestamp Basically we can generate timestamp when this document is inserted by converting the objectid to timestamp: Please look at the following for javascript by  Steve Ridout  on his blog https://steveridout.github.io/mongo-object-time/ Why generate an ObjectId from a timestamp? To query documents by creation date. e.g. to find all comments created after 2013-11-01: db.comments.find({_id: {$gt: ObjectId("5272e0f00000000000000000")}}) Javascript functions var objectIdFromDate = function (date) { return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000"; }; var dateFromObjectId = function (objectId) { return new Date(parseInt(objectId.substring(0, 8), 16) * 1000); };
This is what we are looking to update db.getCollection('location').find({"correlationId.correlation":"MN09"}) Result: { "_id" : ObjectId("4523452345235234"), "correlationId" : { "correlation" : "MN09" }, "sortSequence" : 120, "code" : "MN09", "description" : "Manhattan 9", "legacyZone" : "West", "locationTypeId" : { "correlation" : "DISTRICT" }, "garageCode" : "MW09G", "servicesSelf" : true, "servicedBy" : [ { "correlation" : "MN12" } ], "workUnit" : { "correlation" : "MNBO" } } we would like to do a find and update on "servicedBy" : [ { "correlation" : "MN12" } ] using db.getCollection('location').update( {"correlationId.correlation":"MN09"}, { $set : { ...