ple*_*dez 4 javascript python date mongodb
我是MongoDB的新手,我坚持使用String to Date转换.在db中,日期项以String类型存储为"date":"2015-06-16T17:50:30.081Z"
我想按日期对文档进行分组并计算每天的总和,因此我必须从日期字符串中提取年,月和日,并擦除小时,分钟和秒.我尝试了多种方式,但它们要么返回1970-01-01的日期类型,要么返回当前日期.
此外,我想将以下mongo查询转换为python代码,这给我带来了同样的问题,我无法在python中调用javascript函数,datetime也无法解析mongo语法$date.
我试过了:
new Date("2015-06-16T17:50:30.081Z")
new Date(Date.parse("2015-06-16T17:50:30.081Z"))
etc...
Run Code Online (Sandbox Code Playgroud)
我很好地发现如果字符串是用Javascript或Python给出的,我知道解析它的方法不止一种.但是我不知道如何在MongoDB查询中执行此操作.
db.collection.aggregate([
{
//somthing
},
{
'$group':{
'_id':{
'month': (new Date(Date.parse('$approTime'))).getMonth(),
'day': (new Date(Date.parse('$approTime'))).getDate(),
'year': (new Date(Date.parse('$approTime'))).getFullYear(),
'countries':'$countries'
},
'count': {'$sum':1}
}
}
])
Run Code Online (Sandbox Code Playgroud)
如果您可以确定输入日期字符串的格式并且您只是想获得唯一YYYYMMDD的计数,那么只需$ item上的子字符串和组:
var data = [
{ "name": "buzz", "d1": "2015-06-16T17:50:30.081Z"},
{ "name": "matt", "d1": "2018-06-16T17:50:30.081Z"},
{ "name": "bob", "d1": "2018-06-16T17:50:30.081Z"},
{ "name": "corn", "d1": "2019-06-16T17:50:30.081Z"},
];
db.foo.drop();
db.foo.insert(data);
db.foo.aggregate([
{ "$project": {
"xd": { "$substr": [ "$d1", 0, 10 ]}
}
},
{ "$group": {
"_id": "$xd",
"n": {$sum: 1}
}
}
]);
{ "_id" : "2019-06-16", "n" : 1 }
{ "_id" : "2018-06-16", "n" : 2 }
{ "_id" : "2015-06-16", "n" : 1 }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4327 次 |
| 最近记录: |