Mongodb排序内部数组

时间:2013-03-13 14:28:33

标签: mongodb aggregation-framework

我一直在寻找一段时间,似乎无法对内部数组进行排序,并将其保留在我正在使用的文档中。

{
    "service": {
        "apps": {
            "updates": [
              {
                "n" : 1
                "date": ISODate("2012-03-10T16:15:00Z")
              },
              {
                "n" : 2
                "date": ISODate("2012-01-10T16:15:00Z")
              },
              {
                "n" : 5
                "date": ISODate("2012-07-10T16:15:00Z")
              }
            ]
        }
     }
 }

所以我想保留要作为服务返回的项目,但我的更新数组已排序。到目前为止,我有shell:

db.servers.aggregate(
        {$unwind:'$service'},
        {$project:{'service.apps':1}},
        {$unwind:'$service.apps'}, 
        {$project: {'service.apps.updates':1}}, 
        {$sort:{'service.apps.updates.date':1}});

有人认为他们可以提供帮助吗?

2 个答案:

答案 0 :(得分:40)

您可以$unwind updates数组执行此操作,按date对结果文档进行排序,然后$group_id重新组合在一起db.servers.aggregate( {$unwind: '$service.apps.updates'}, {$sort: {'service.apps.updates.date': 1}}, {$group: {_id: '$_id', 'updates': {$push: '$service.apps.updates'}}}, {$project: {'service.apps.updates': '$updates'}}) 使用排序顺序。

{{1}}

答案 1 :(得分:5)

Mongo 4.4开始,$function聚合运算符允许应用自定义javascript函数来实现MongoDB查询语言不支持的行为。

例如,为了按照对象的字段之一对数组进行排序:

// {
//   "service" : { "apps" : { "updates" : [
//     { "n" : 1, "date" : ISODate("2012-03-10T16:15:00Z") },
//     { "n" : 2, "date" : ISODate("2012-01-10T16:15:00Z") },
//     { "n" : 5, "date" : ISODate("2012-07-10T16:15:00Z") }
//   ]}}
// }
db.collection.aggregate(
  { $set: {
    { "service.apps.updates":
      { $function: {
          body: function(updates) {
            updates.sort((a, b) => a.date - b.date);
            return updates;
          },
          args: ["$service.apps.updates"],
          lang: "js"
      }}
    }
  }
)
// {
//   "service" : { "apps" : { "updates" : [
//     { "n" : 2, "date" : ISODate("2012-01-10T16:15:00Z") },
//     { "n" : 1, "date" : ISODate("2012-03-10T16:15:00Z") },
//     { "n" : 5, "date" : ISODate("2012-07-10T16:15:00Z") }
//   ]}}
// }

这将修改数组的位置,而不必应用昂贵的$unwind$sort$group阶段的组合。

$function具有3个参数:

  • body,这是要应用的函数,其参数是要修改的数组。
  • args,其中包含body函数作为参数的记录中的字段。在我们的情况下,"$service.apps.updates"
  • lang,这是编写body函数的语言。当前仅js可用。