使用$natural在MongoDB中进行自然排序。让我们创建一个包含文档的集合-
> db.demo684.insertOne({Value:10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530cea7e81adc6a0b3957") } > db.demo684.insertOne({Value:50}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d1a7e81adc6a0b3958") } > db.demo684.insertOne({Value:60}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d4a7e81adc6a0b3959") } > db.demo684.insertOne({Value:40}); { "acknowledged" : true, "insertedId" : ObjectId("5ea530d8a7e81adc6a0b395a") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo684.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
以下是根据_id排序的查询-
> db.demo684.find(). sort({'_id': 1});
这将产生以下输出-
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }
您还可以使用$natural-
> db.demo684.find().sort({$natural: 1});
这将产生以下输出-
{ "_id" : ObjectId("5ea530cea7e81adc6a0b3957"), "Value" : 10 } { "_id" : ObjectId("5ea530d1a7e81adc6a0b3958"), "Value" : 50 } { "_id" : ObjectId("5ea530d4a7e81adc6a0b3959"), "Value" : 60 } { "_id" : ObjectId("5ea530d8a7e81adc6a0b395a"), "Value" : 40 }