要对ObjectId列执行排序,请使用sort()
。让我们用文档创建一个集合。
> db.demo403.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b0fac4d418a017858e") } > db.demo403.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b2fac4d418a017858f") } > db.demo403.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b5fac4d418a0178590") } > db.demo403.insertOne({"Name":"Adam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e6f89b8fac4d418a0178591") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo403.find();
这将产生以下输出-
{ "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" } { "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" } { "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" } { "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" }
以下是对MongoDB中的ObjectId列执行排序的查询-
> db.demo403.find().sort({_id:-1});
这将产生以下输出-
{ "_id" : ObjectId("5e6f89b8fac4d418a0178591"), "Name" : "Adam" } { "_id" : ObjectId("5e6f89b5fac4d418a0178590"), "Name" : "Bob" } { "_id" : ObjectId("5e6f89b2fac4d418a017858f"), "Name" : "David" } { "_id" : ObjectId("5e6f89b0fac4d418a017858e"), "Name" : "Chris" }