首页 > 解决方案 > 根据数组元素日期时间和字段对文档进行聚合和排序

问题描述

目前我有以下架构:

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}]}

任何人都可以提出解决方案吗?

标签: node.jsmongodbmongoose

解决方案


以下查询将返回匹配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
    }
  }
])

如果条件有任何更改,请告诉我,我将尝试重新调整查询。


推荐阅读