如何在 pymongo 管道中创建日期时间对象?
How to create a datetime object within a pymongo pipeline?
我在一些代码中设置了以下管道:过滤器集合、项目年份和月份、按年份和月份分组,然后以 YYYY-MM-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": {
"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-24
转换为 2015-12-01
,我修改了 code on this page 如下:
示例文档:
{
_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"}
}
我在一些代码中设置了以下管道:过滤器集合、项目年份和月份、按年份和月份分组,然后以 YYYY-MM-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": {
"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-24
转换为 2015-12-01
,我修改了 code on this page 如下:
示例文档:
{
_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"}
}