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-ae32-f0896e79ca39"
    },
    {
        "_id" : "d0e8bd76-154c-41bf-bdd4-858254491ddd"
    },
    {
        "_id" : "32f54f4d-5cba-4a6d-a423-91caa05277f9"
    },
.
.
]

// using the map function, we can return only the value and store them in an array, this is useful when we want to subject this array to a simple $in operator.

var newArray = updateArray.map( function(item)  { return item._id });
newArray;

[
    "5680e9b8-6ffe-41bb-a035-e255ede87b8e",
    "08b08206-f2a7-49b8-bf7a-b72a6494e556",
    "17e49c0d-0892-4f4b-a0c5-effaaf07a058",
    "1b1756ce-63fe-4b9e-baf3-e2f418feb3d7",
    "e31a02f6-e217-4172-bcf5-684ab40321de",
    "01f6fcab-4123-44aa-ae32-f0896e79ca39",
    "d0e8bd76-154c-41bf-bdd4-858254491ddd",
    "32f54f4d-5cba-4a6d-a423-91caa05277f9",
    "58ee1a2f-aad6-4e33-baa4-a04adf6b7a9c",
    "92c19f6e-206a-400f-93ca-12565019fb6a",
    "4382d2b0-9e25-4ac1-a5e6-74a22de23fc0",
    "7d300862-67f9-4716-a02c-318246dd3e4b",
    "40d44db1-8347-4be6-89bf-a4fe9a49aad2",
.
.
]

example of how we can leverage the newly formed array:

db.getSiblingDB("equipment").detachment.updateMany( { _id: {$in: newArray}}, {$set: { refreshDate: dayToRefreshTo}});

Comments

Popular posts from this blog

MongoDB tip: 4 ways to modify replica set configuration

MongoDB Quick Note: BI Connector Issue

MongoDB Tips: Kill long running processes