【问题标题】:nodejs+moongose sort inner array by element timestampnode js+mongoose按元素时间戳对内部数组进行排序
【发布时间】:2018-01-29 17:04:38
【问题描述】:

我有以下架构:

  var VisionsystemSchema = new mongoose.Schema({
  linenumber: {
    type: String,
    index: true,
    unique: true
  },
  name: String,
  rois: [
    {
      name: String,
      history: [Date, Number]
    }
  ]
});

对于 rois 数组中的每个元素,我都有一个带有 [date,number] 元组的历史值数组。如何按日期第一个元素对历史数组进行排序?

【问题讨论】:

  • Mongodb sort inner array的可能重复
  • veeram 提到的问题包括对内部数组进行排序
  • 第一个元素日期是最大或最小日期还是某个随机日期?
  • @Veeram 是一个随机日期

标签: node.js mongodb sorting mongoose


【解决方案1】:

您可以使用以下聚合查询。

$unwind rois 数组,然后按第一个元素对文档进行排序,$group 返回 _id 以获取排序后的数组。

db.col.aggregate([
  {"$unwind":"$rois"},
  {"$sort":{"rois.history.0":-1}},
  {"$group":{"_id":"$_id","rois":{"$push":"$rois.history"}}}
])

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多