node.js - 根据数组元素日期时间和字段对文档进行聚合和排序
问题描述
目前我有以下架构:
User:{
verified:boolean,
history:[{
type:string,
dateTime:datetime
}]
}
我需要根据 history.type 和 history.datetime 对数据进行聚合和排序。例如,我有 100 个文档。其中一半有 history.type="Testing" 并且每个历史都有自己的日期时间。我需要匹配历史类型并使用猫鼬 nodejs 对日期时间进行排序。
这是我所做的,但没有按预期工作:
let user = await User.aggregate([
{
$match: {
"nameVerified":true,
'history.type' : 'NAME_VERIFIED'
}
},
{$unwind: '$history'},
{
$match: {
'history.type' : 'NAME_VERIFIED'
}
},
{
$group : {
_id :'$_id'
}
},
{
$sort:
{
'history.dateTime': -1
}
}]);
样本数据:
{_id:1,verified:false,history:[...]}
{_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
{_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
{_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
{_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
预期成绩:
{_id:3,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-24},{type:"TEST",dateTime:2018-10-21}]}
{_id:2,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-23},{type:"TEST",dateTime:2018-10-25}]}
{_id:5,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-22},{type:"TEST",dateTime:2018-10-21}]}
{_id:4,verified:true,history:[{type:"NAME_VERIFIED",dateTime:2018-10-21},{type:"TEST",dateTime:2018-10-21}]}
任何人都可以提出解决方案吗?
解决方案
以下查询将返回匹配history.type
并按 排序的文档数组history.dateTime
。
User.aggregate([{
$match: {
"history.type": 'NAME_VERIFIED',
}
},
{
$unwind: '$history'
},
{
$match: {
"history.type": 'NAME_VERIFIED',
}
},
{
$sort: {
'history.dateTime': -1
}
},
{
$group: {
'_id': {
'_id': '$_id',
'verified': '$verified'
},
'history': {
'$push': '$history'
}
}
},
{
$project: {
'_id': '$_id._id',
'verified': '$_id.verified',
'history': 1
}
}
])
如果条件有任何更改,请告诉我,我将尝试重新调整查询。
推荐阅读
- c# - 将 C# 转换为 Visual Basic Shopify WebRequests 停止运行
- javascript - 为什么变量没有在 created() 方法中定义
- postgresql - 如何在没有 pg_dump 的情况下将我的所有表从 Postgres 数据库复制到另一个?
- javascript - 如何调整模态框的大小?
- java - spring boot 中创建预定方法的最佳实践
- python-3.x - python Osmnx上的RuntimeError
- html - 侧面固定菜单在 div 下方重叠
- cmd - 等到程序启动
- python - 使用python比较excel中的两列和颜色更大?
- python - imageio:AttributeError:“模块”对象没有属性“imread”