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

mongodb sorting children of an array in a document

我的数据是这样的:

{
    "name":"dan",
    "somestring":"asdf",
    "friends":[

            {
                "name": "carl",
                "height":180,
                ...
            },
            {
                "name": "john",
                "height":165,
                ...
            },
            {
                "name": "jim",
                "height":170,
                ...
            }

    ]
},
...

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

我试过db.getCollection('users').find({"name" : "dan"}, {"friends" : 1}).sort({"friends.height" : -1}),但好友列表保持不变。

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

一个选项是 运行 聚合:

  1. 展开数组
  2. friends.name
  3. 排序
  4. 重组

管道应如下所示:

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