I made a script in local development machine mongoDb 4.0 its working flawless but for client server MongoDb is 2.6 so $dateToString is not supported. is there any substitute using $dateToString into mongoDb 2.6.
Using MongoDb 4.0 :
db.getCollection('orgData').aggregate([
{$match:{'orgId' : 5} },
{$unwind :'$events.click'},
{'$project' :{'events.click' : 1}},
{$group :{
'_id' :{'$dateToString' : {format: "%Y-%m-%d",date:'$events.click.mongo_datetime'} }
,'count' : {'$sum' : 1}
}}
]);
Output :
/* 1 */
{
"_id" : "2019-03-01",
"count" : 1427.0
}
/* 2 */
{
"_id" : "2019-02-28",
"count" : 2244.0
}
But in MongoDb 2.6 Iam getting Error :
assert: command failed: {
"errmsg" : "exception: invalid operator '$dateToString'",
"code" : 15999,
"ok" : 0
} : aggregate failed
Error: command failed: {
"errmsg" : "exception: invalid operator '$dateToString'",
"code" : 15999,
"ok" : 0
} : aggregate failed
at Error (<anonymous>)
at doassert (src/mongo/shell/assert.js:11:14)
at Function.assert.commandWorked (src/mongo/shell/assert.js:244:5)
at DBCollection.aggregate (src/mongo/shell/collection.js:1149:12)
at (shell):1:29
2019-09-13T17:28:57.980+1000 Error: command failed: {
"errmsg" : "exception: invalid operator '$dateToString'",
"code" : 15999,
"ok" : 0
} : aggregate failed at src/mongo/shell/assert.js:13
Database design :
In MongoDB 2.6 you would need to use the date operators together with the string operator $concat
to achieve the desired expression
as substitute. Consider the following example :
db.getCollection('orgData').aggregate([
{ '$match': { 'orgId' : 5 } },
{ '$unwind': '$events.click' },
{ '$group' :{
'_id': {
'$concat': [
{ '$substr': [
{ '$year': '$events.click.mongo_datetime' },
0,4
] },
'-',
{ '$substr': [
{ '$month': '$events.click.mongo_datetime' },
0,2
] },
'-',
{ '$substr': [
{ '$dayOfMonth': '$events.click.mongo_datetime' },
0,2
] }
]
},
'count': { '$sum' : 1 }
} }
]);
Note: the $project
pipeline stage becomes redundant if used before a $group
pipeline step since $group
will change the document schema as a result.