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 } )