要进行排序,请在MongoDB中使用sort()。让我们创建一个包含文档的集合-
> db.demo755.insertOne({"Value":10}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e72a930c785c834e572") } > db.demo755.insertOne({"Value":10.5}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e75a930c785c834e573") } > db.demo755.insertOne({"Value":9.5}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e79a930c785c834e574") } > db.demo755.insertOne({"Value":12.5}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e7fa930c785c834e575") } > db.demo755.insertOne({"Value":11.5}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e87a930c785c834e576") } > db.demo755.insertOne({"Value":6}); { "acknowledged" : true, "insertedId" : ObjectId("5eae9e97a930c785c834e577") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo755.find();
这将产生以下输出-
{ "_id" : ObjectId("5eae9e72a930c785c834e572"), "Value" : 10 } { "_id" : ObjectId("5eae9e75a930c785c834e573"), "Value" : 10.5 } { "_id" : ObjectId("5eae9e79a930c785c834e574"), "Value" : 9.5 } { "_id" : ObjectId("5eae9e7fa930c785c834e575"), "Value" : 12.5 } { "_id" : ObjectId("5eae9e87a930c785c834e576"), "Value" : 11.5 } { "_id" : ObjectId("5eae9e97a930c785c834e577"), "Value" : 6 }
以下是对包含整数和小数值的MongoDB字段进行排序的查询-
> db.demo755.find().sort({Value:1});
这将产生以下输出-
{ "_id" : ObjectId("5eae9e97a930c785c834e577"), "Value" : 6 } { "_id" : ObjectId("5eae9e79a930c785c834e574"), "Value" : 9.5 } { "_id" : ObjectId("5eae9e72a930c785c834e572"), "Value" : 10 } { "_id" : ObjectId("5eae9e75a930c785c834e573"), "Value" : 10.5 } { "_id" : ObjectId("5eae9e87a930c785c834e576"), "Value" : 11.5 } { "_id" : ObjectId("5eae9e7fa930c785c834e575"), "Value" : 12.5 }