我有一个名为“捕获”的集合,其中的文档具有“用户名”字段
一个文件看起来像这样
/* 1 */
{
"_id" : ObjectId("622b951a026ca3a73f5a2a1c"),
"username" : "andre",
"data" : {
"metadata" : {
"start" : "2022-02-24T09:32:22.390Z",
...
},
...
}
}
/* 2 */
{
"_id" : ObjectId("9255941b026ca3a73f5a2a1c"),
"username" : "andre",
"data" : {
"metadata" : {
"start" : "2022-05-10T03:12:23.440Z",
...
},
...
}
}
/* 3 */
{
"_id" : ObjectId("7775941b026ca3a73f5a2a1c"),
"username" : "bob",
"data" : {
"metadata" : {
"start" : "2022-05-16T12:24:12.002Z",
...
},
...
}
}
/* 4 */
{
"_id" : ObjectId("3215331b026ca3a73f5a2a1c"),
"username" : "bob",
"data" : {
"metadata" : {
"start" : "2022-05-18T12:24:12.002Z",
...
},
...
}
}
我想返回每个不同用户名的文档计数,其中“开始”在 2022-02-24T09:32:22.390Z 之后
上面的示例将返回如下内容:
{ "user" : "andre", "count" : 1 }
{ "user" : "bob", "count" : 2 }
我试过使用count,distinct,aggregate没有成功......
回答1
使用聚合框架非常简单:
[
{
$project: {
_id: 0,
user: '$username',
start: {
$toDate: '$data.metadata.start'
}
}
},
{
$match: {
start: {
$gt: Date('2022-02-24T09:32:22.390Z')
}
}
},
{
$group: {
_id: '$user',
user: {
$first: '$user'
},
count: {
$sum: 1
}
}
}
]
顺便说一句,您应该将 store dates 作为 Date 对象,而不是字符串,这将使您的生活更轻松。