我有一些代码设置了以下管道: filter集合、项目年和月、按年和月分组,然后使用像YYYY 01这样的datetime对象结束。
示例文档:
{
_id: 123456
foo: "bar"
dt: ISODate("2015-12-24T11:59:00Z")
}示例代码:
from pymongo import MongoClient
db = client.testDB
posts = db.testCollection
pipeline = [
{"$match": {"foo":"bar"}},
{"$project": {
"year": {"$year": "$dt"},
"month": {"$month": "$dt"},
}
},
{"$group": {
"_id": { "dt": ??? },
"totalCount": { "$sum": 1 }
}
},
{"$out": "myResults"}
}
posts.aggregate(pipeline)目标:
{
_id: {dt: ISODate("2015-12-01T00:00:00Z")}
totalCount: 8
}发布于 2015-12-27 10:28:51
为了将日期预测到一个月的第一个月,例如,将2015-12-24转换为2015-12-01,我对此页上的代码进行了如下修改:
示例文档:
{
_id: 123456
foo: "bar"
dt: ISODate("2015-12-24T11:59:00Z")
}代码:
from pymongo import MongoClient
db = client.testDB
posts = db.testCollection
pipeline = [
{"$match": {"foo":"bar"}},
{
"$project": {
"dt": "$dt"
"d": {"$dayOfMonth": "$dt"},
"h": {"$hour": "$dt"},
"m": {"$minute": "$dt"},
"s": {"$second": "$dt"},
"ml": {"$millisecond": "$dt"},
}
},
{
"$group": {
"_id": {
"$subtract": [
"$dt",
{
"$add": [
"$ml",
{"$multiply": ["$s", 1000]},
{"$multiply": ["$m", 60, 1000]},
{"$multiply": ["$h", 60, 60, 1000]},
{"$multiply": [{"$subtract": ["$d", 1]}, 24, 60, 60, 1000]},
]
}
]
},
"totalCount": { "$sum": 1 }
}
},
{"$out": "myResults"}
}https://stackoverflow.com/questions/34430020
复制相似问题