要对值排序,请sort()
在MongoDB中使用。首先让我们创建一个包含文档的集合-
> db.demo365.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5b6d0ada61456dc936f") } > db.demo365.insertOne({"FirstName":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5bad0ada61456dc9370") } > db.demo365.insertOne({"FirstName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5bed0ada61456dc9371") } > db.demo365.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e57d5c0d0ada61456dc9372") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo365.find();
这将产生以下输出-
{ "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" } { "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" } { "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" } { "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" }
以下是排序查询-
> db.demo365.find().sort({"FirstName":1});
这将产生以下输出-
{ "_id" : ObjectId("5e57d5bad0ada61456dc9370"), "FirstName" : "Adam" } { "_id" : ObjectId("5e57d5c0d0ada61456dc9372"), "FirstName" : "Bob" } { "_id" : ObjectId("5e57d5b6d0ada61456dc936f"), "FirstName" : "Chris" } { "_id" : ObjectId("5e57d5bed0ada61456dc9371"), "FirstName" : "John" }