In my MongoDB collection, I have documents that are structured as follows:
{
"gran": "Day",
"dix": NumberInt(80),
"y": NumberInt(2017),
},
{
"gran": "Month",
"dix": NumberInt(3),
"y": NumberInt(2017),
}
I am looking to enhance these documents by adding a from/to field, resulting in the following format:
{
"gran": "Day",
"dix": NumberInt(80),
"y": NumberInt(2017),
"from": ISODate("2017-03-21T00:00:00.000+0000"),
"to": ISODate("2017-03-21T23:59:59.000+0000")
},
{
"gran": "Month",
"dix": NumberInt(3),
"y": NumberInt(2017),
"from": ISODate("2017-03-01T00:00:00.000+0000"),
"to": ISODate("2017-03-31T23:59:59.000+0000")
}
To achieve this, I created a JavaScript function that translates granularities into dates:
function(year, index, gran) {
// Function logic here
}
For updating the documents with the from/to fields, I initially attempted using this method:
db.reports.findAndModify({
query: { "from": {$exists: false}},
update: {
$set: {
"from": new Date(),
"to": new Date()
}
},
multi: true
})
Upon exploring further options, I tried utilizing the following approach:
db.reports.aggregate([
{
$match:
{
}
}
]).map(function(doc) {
// Mapping logic here
})
However, the above method did not yield the desired results of dynamically updating the documents within the collection. Any suggestions on how I can effectively apply the script I developed for document updates?
Note that I am working with MongoDB version 3.2 and unable to upgrade to version 3.4 at this time, ruling out the use of $addFields in an aggregation pipeline.