Để sắp xếp các bản ghi trong một bộ sưu tập, hãy sử dụng sort () trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo32.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e175158cfb11e5c34d898c5")
}
> db.demo32.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17515ccfb11e5c34d898c6")
}
> db.demo32.insertOne({"Name":"Adam"});
{
"acknowledged" : true,
"insertedId" : Object0Id("5e175160cfb11e5c34d898c7")
}
> db.demo32.insertOne({"Name":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e175165cfb11e5c34d898c8")
}
> db.demo32.insertOne({"Name":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e17517bcfb11e5c34d898c9")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo32.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" } Sau đây là truy vấn để thực hiện sắp xếp trong MongoDB -
> db.demo32.find().sort({"Name":1}); Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e175160cfb11e5c34d898c7"), "Name" : "Adam" }
{ "_id" : ObjectId("5e17515ccfb11e5c34d898c6"), "Name" : "Bob" }
{ "_id" : ObjectId("5e17517bcfb11e5c34d898c9"), "Name" : "Carol" }
{ "_id" : ObjectId("5e175158cfb11e5c34d898c5"), "Name" : "Chris" }
{ "_id" : ObjectId("5e175165cfb11e5c34d898c8"), "Name" : "John" }