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

问题描述 投票:0回答:1

我有一个像下面这样的集合

{
  _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
}
node.js database mongodb
1个回答
1
投票

没有办法做你想要的。编写数据时无法保证更新顺序。

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

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

//Sort by ascending
db.Collection.find().sort( { addedOn: 1 } )
© www.soinside.com 2019 - 2024. All rights reserved.