使用 MongoDB 对 ID 排序并逆转项目
$natural 按自然顺序返回文档。要逆转项目,请使用 $natural:-1。我们通过文档创建一个集合:
> db.demo710.insertOne({id:101,Name:"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a") } > db.demo710.insertOne({id:102,Name:"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a8d5d33e20ed1097b7b") } > db.demo710.insertOne({id:103,Name:"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a935d33e20ed1097b7c") } > db.demo710.insertOne({id:104,Name:"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5ea83a9b5d33e20ed1097b7d") }
通过 find() 方法显示集合中的所有文档:
> db.demo710.find();
这将产生以下输出:
{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" } { "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" } { "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" } { "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }
以下是查询以对项目进行排序并逆转:
> db.demo710.find().sort({$natural:-1});
这将产生以下输出:
{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" } { "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" } { "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" } { "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }
广告