Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.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 如何在mongoDB中对文档进行排序?_Node.js_Database_Mongodb - Fatal编程技术网

Node.js 如何在mongoDB中对文档进行排序?

Node.js 如何在mongoDB中对文档进行排序?,node.js,database,mongodb,Node.js,Database,Mongodb,我有一个像下面这样的收藏 { _id: ObjectId('1asad23dsa45'), name: 'demo', addedOn: 1550228980162, // this is timestamp }, { _id: ObjectId('12das34fda6'), name: 'demo2', addedOn: 1550228980156, // this is timestamp }, { _id: ObjectId('12asd34fs6dfa'),

我有一个像下面这样的收藏

{
  _id: ObjectId('1asad23dsa45'),
  name: 'demo',
  addedOn: 1550228980162, // this is timestamp
},
{
  _id: ObjectId('12das34fda6'),
  name: 'demo2',
  addedOn: 1550228980156, // this is timestamp
},
{
  _id: ObjectId('12asd34fs6dfa'),
  name: 'demo3',
  addedOn: 1550228980160, // this is timestamp
}
我想更新所有文档,以便所有文档都按时间戳键排序

因此,更新后的文档可能如下所示

{
  _id: ObjectId('1asad23dsa45'),
  name: 'demo',
  addedOn: 1550228980162, // this is timestamp
},
{
  _id: ObjectId('12asd34fs6dfa'),
  name: 'demo3',
  addedOn: 1550228980160, // this is timestamp
},
{
  _id: ObjectId('12das34fda6'),
  name: 'demo2',
  addedOn: 1550228980156, // this is timestamp
}

没有办法做你要求的事。您无法保证写入数据时更新的顺序

但是,在读取数据和准备查询时,始终可以使用

//Sort by descending
db.Collection.find().sort( { addedOn: -1 } )

//Sort by ascending
db.Collection.find().sort( { addedOn: 1 } )