简体   繁体   English

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

[英]How to sort documents in mongoDB?

I have a collection like below 我有如下收藏

{
  _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
}

I want to update all documents in such as way that all gets sorted by timestamp key 我想更新所有文档,例如按时间戳键对所有文档进行排序

so after update the document may look like this 所以更新后的文件可能看起来像这样

{
  _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
}

There is no way to do what you are asking for. 没有办法去做你想要的。 You cannot guarantee the order of updates while writing data. 写入数据时,不能保证更新的顺序。

However, you can always use sort while reading data and preparing queries. 但是,在读取数据和准备查询时,您始终可以使用sort

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM