Computer >> Máy Tính >  >> Lập trình >> MongoDB

Hiển thị bản ghi MongoDB có thứ tự rõ ràng với bỏ qua và giới hạn?

Bạn có thể làm việc với khuôn khổ tổng hợp và sử dụng $ sort, $ bỏ qua và $ giới hạn để hiển thị các bản ghi có thứ tự rõ ràng với bỏ qua và cũng đặt giới hạn. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu

> db.orderedDistinctDemo.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8e0140b992277dae0e9")
}
> db.orderedDistinctDemo.insertOne({"Name":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8e5140b992277dae0ea")
}
> db.orderedDistinctDemo.insertOne({"Name":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8e7140b992277dae0eb")
}
> db.orderedDistinctDemo.insertOne({"Name":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8ea140b992277dae0ec")
}
> db.orderedDistinctDemo.insertOne({"Name":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8ee140b992277dae0ed")
}
> db.orderedDistinctDemo.insertOne({"Name":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8f2140b992277dae0ee")
}
> db.orderedDistinctDemo.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8f6140b992277dae0ef")
}
> db.orderedDistinctDemo.insertOne({"Name":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccfb8f9140b992277dae0f0")
}

Sau đây là truy vấn để 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.orderedDistinctDemo.find().pretty();

Điều này sẽ tạo ra kết quả sau -

{ "_id" : ObjectId("5ccfb8e0140b992277dae0e9"), "Name" : "John" }
{ "_id" : ObjectId("5ccfb8e5140b992277dae0ea"), "Name" : "Larry" }
{ "_id" : ObjectId("5ccfb8e7140b992277dae0eb"), "Name" : "Larry" }
{ "_id" : ObjectId("5ccfb8ea140b992277dae0ec"), "Name" : "Sam" }
{ "_id" : ObjectId("5ccfb8ee140b992277dae0ed"), "Name" : "John" }
{ "_id" : ObjectId("5ccfb8f2140b992277dae0ee"), "Name" : "Carol" }
{ "_id" : ObjectId("5ccfb8f6140b992277dae0ef"), "Name" : "David" }
{ "_id" : ObjectId("5ccfb8f9140b992277dae0f0"), "Name" : "Carol" }

Đây là truy vấn để hiển thị bản ghi có thứ tự rõ ràng với bỏ qua và giới hạn -

> db.orderedDistinctDemo.aggregate(
...    { $group : { _id : "$Name" }},
...    { $sort : { _id: 1 }},
...    { $skip : 3 },
...    { $limit : 8 }
... );

Điều này sẽ tạo ra kết quả sau -

{ "_id" : "Larry" }
{ "_id" : "Sam" }