$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" }