我有一个像下面这样的集合
{
_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。
//Sort by descending
db.Collection.find().sort( { addedOn: -1 } )
//Sort by ascending
db.Collection.find().sort( { addedOn: 1 } )