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

时间:2019-02-15 11:13:07

标签: 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'),
  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
}

1 个答案:

答案 0 :(得分:1)

无法完成您所要的。您不能保证写入数据时的更新顺序。

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

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

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