mongodb - Mongodb查询没有返回我想要的
问题描述
我正在尝试返回所有最新创建的 appUserID。
Created 是他们制作的最后一条记录的时间戳
db.getCollection('<my collection>').aggregate([{
'$match': {
'$and': [
{
'companyID': < company ID >
},
{
'created': {
'$gte': < startDate timestamp >
}
},
{
'created': {
$lt: < endDate timestamp >
}
}
]
}
}, {
'$project': {
'appUserID': 1
}
}, {
'$group': {
'_id': '$appUserID',
'registrationsCount': {
'$sum': 1
},
},
}, {
'$sort': {
'registrationsCount': - 1
}
}])
这当前返回 appuserID 和 registrationCount 并对其进行排序,但我无法返回 appuserID 和最新的时间戳
解决方案
发生这种情况是因为您使用投影删除了必填字段:
{
'$project': {
'appUserID': 1
}
}
该指令将清除除 . 之外的所有字段appUserID
。为了能够进行最新的时间戳计算,您必须将其保存在聚合管道中:
{
'$project': {
'appUserID': 1,
'created' : 1
}
}, {
'$group': {
'_id': '$appUserID',
'registrationsCount': {
'$sum': 1
},
'latest': {
$max: '$created'
}
},
}
我使用created
了字段,但你可以使用任何你想要的。
结果将如下所示:
{
"_id" : <some id>,
"registrationsCount" : <count>,
"latest" : <some date>
}
推荐阅读
- ios - Swift - 可选属性的 JSON 序列化
- network-programming - Ansible 路由器模板生成器 - vars_prompt 的问题
- python-3.x - 底图不显示绘制的数据(如果完全绘制)
- java - SOAP - 空体
- python - 根据其他列的 groupby 为列设置值
- javascript - javascript - 多个移动墙
- keras - 在 keras 中获得相同模型 FFNN 的不同结果
- python - Pythonista 如何在 App Store 限制中工作?
- swift - 使用研究工具包不能跳过一个步骤
- python - 如何使用 BeautifulSoup 查找元素的父标签?