mongodb对文档中数组的子进行排序

时间:2017-06-28 08:21:12

标签: arrays mongodb sorting children

我的数据如下:

db.getCollection('users').find({"name" : "dan"}, {"friends" : 1}).sort({"friends.height" : -1})

我想检索朋友按高度降序排序的文档。

我尝试<i>html</i> <strong>html</strong> <em>html</em> <b>html</b> ,但朋友列表保持不变。

编辑:我弄乱了数据的结构,我修复了数组看起来像一个数组......

1 个答案:

答案 0 :(得分:3)

选项是运行以下聚合:

  1. 展开数组
  2. friends.name
  3. 排序
  4. 重新组合
  5. 管道应如下所示:

    db.collection.aggregate([
        { $match: { name: 'dan' }},
        { $unwind: '$friends' },
        { $sort: { 'friends.height': -1 }},
        { $group: { _id: '$name', friends: { $push: '$friends'}}])