简体   繁体   中英

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 by descending
db.Collection.find().sort( { addedOn: -1 } )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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