Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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
Node.js 如何使用NodeJS按数组中的第n项对mongo数据库进行排序?_Node.js_Arrays_Mongodb_Sorting - Fatal编程技术网

Node.js 如何使用NodeJS按数组中的第n项对mongo数据库进行排序?

Node.js 如何使用NodeJS按数组中的第n项对mongo数据库进行排序?,node.js,arrays,mongodb,sorting,Node.js,Arrays,Mongodb,Sorting,例如,数据库如下所示 { id: 1, counter: [2,6] }, { id: 2, counter: [5,10] }, { id: 3, counter: [1,3] } { id: 2, counter: [5,10] }, { id: 1, counter: [2,6] }, { id: 3, counter: [1,3] } 现在我想按每个数组中的第二项对其进行排序,结果如下 { id: 1, counter: [2,

例如,数据库如下所示

{
  id: 1,
  counter: [2,6]
},
{
  id: 2,
  counter: [5,10]
},
{
  id: 3,
  counter: [1,3]
}
{
  id: 2,
  counter: [5,10]
},
{
  id: 1,
  counter: [2,6]
},
{
  id: 3,
  counter: [1,3]
}
现在我想按每个数组中的第二项对其进行排序,结果如下

{
  id: 1,
  counter: [2,6]
},
{
  id: 2,
  counter: [5,10]
},
{
  id: 3,
  counter: [1,3]
}
{
  id: 2,
  counter: [5,10]
},
{
  id: 1,
  counter: [2,6]
},
{
  id: 3,
  counter: [1,3]
}

有人知道如何做到这一点吗?

您可以使用sort属性

const数据=[{
id:2,
柜台:[5,10]
},
{
id:1,
柜台:[2,6]
},
{
id:3,
柜台:[1,3]
}]
数据排序((a,b)=>{
返回a.计数器[1]>b.计数器[1]
})

console.log(数据)
您可以使用聚合管道:

  • $addFields
    添加新字段
    分拣机
    ,该字段将等于数组的第二项
  • $sort
    根据新字段对结果进行排序
  • $project
    指定从结果返回哪些属性

下面是一个工作示例:

谢谢你的想法,但是我在这个数据库中有20000个文档,所以这不是一个非常有效的好主意!