Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays mongodb对文档中数组的子级进行排序_Arrays_Mongodb_Sorting_Children - Fatal编程技术网

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

Arrays mongodb对文档中数组的子级进行排序,arrays,mongodb,sorting,children,Arrays,Mongodb,Sorting,Children,我的数据如下所示: { "name":"dan", "somestring":"asdf", "friends":[ { "name": "carl", "height":180, ... }, { "name": "john", "heig

我的数据如下所示:

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

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

    ]
},
...
db.collection.aggregate([
    { $match: { name: 'dan' }},
    { $unwind: '$friends' },
    { $sort: { 'friends.height': -1 }},
    { $group: { _id: '$name', friends: { $push: '$friends'}}])
我想检索按高度递减排序的朋友的文档

我尝试了
db.getCollection('users')。查找({“name”:“dan”},{“friends”:1})。排序({“friends.height”:-1})
,但好友列表保持不变


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

一个选项是运行一个聚合:

  • 展开阵列
  • 按朋友排序。姓名
  • 重组
  • 管道应如下所示:

    {
        "name":"dan",
        "somestring":"asdf",
        "friends":[
    
                {
                    "name": "carl",
                    "height":180,
                    ...
                },
                {
                    "name": "john",
                    "height":165,
                    ...
                },
                {
                    "name": "jim",
                    "height":170,
                    ...
                }
    
        ]
    },
    ...
    
    db.collection.aggregate([
        { $match: { name: 'dan' }},
        { $unwind: '$friends' },
        { $sort: { 'friends.height': -1 }},
        { $group: { _id: '$name', friends: { $push: '$friends'}}])
    

    这些是子文档对象的“键”。你不能把它们分类。如果您希望按“高度”排序,那么它们本身就需要在“数组”条目中。祝您好运!大多数语言实现“默认”都没有“排序键”。例如,JavaScript当然不是这样。这确实表明你选择的结构是不正确的。命名键基本上是一种“蚂蚁模式”。至少用MongoDB查询肯定不好。我弄乱了结构,编辑…@McDermott另一个解决方案是“插入和排序”,基本上里面的数组是在插入步骤排序的。因此,在执行Find()时,将获取已排序的结果。如果您对这种方法感兴趣,我将尝试安排一个答案。@McDermott我忘了提到“插入和排序”是MongoDB本机支持的。让我知道,如果你有兴趣,我会写一个答复。