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

Nhận tổng số tài liệu với MongoDB trong khi sử dụng giới hạn?

Bạn có thể sử dụng toán tử $ facet cho việc này. Để hiểu khái niệm, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau -

> db.totalDocumentDemo.insertOne({"InstructorId":100,"InstructorName":"Larry","InstructorFav
ouriteSubject":["Java","MongoDB","Python"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76e6701e9c5dd6f1f78274")
}
> db.totalDocumentDemo.insertOne({"InstructorId":200,"InstructorName":"Sam","InstructorFav
ouriteSubject":["SQL Server","C#","Javascript"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c76e69c1e9c5dd6f1f78275")
}

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 (). Truy vấn như sau -

> db.totalDocumentDemo.find().pretty();

Đầu ra

{
   "_id" : ObjectId("5c76e6701e9c5dd6f1f78274"),
   "InstructorId" : 100,
   "InstructorName" : "Larry",
   "InstructorFavouriteSubject" : [
      "Java",
      "MongoDB",
      "Python"
   ]
}
{
   "_id" : ObjectId("5c76e69c1e9c5dd6f1f78275"),
   "InstructorId" : 200,
   "InstructorName" : "Sam",
   "InstructorFavouriteSubject" : [
      "SQL Server",
      "C#",
      "Javascript"
   ]
}

Đây là truy vấn để nhận tổng số tài liệu từ một bộ sưu tập -

> db.totalDocumentDemo.aggregate([
   ... {
      ... $facet:{
         ... Alldata:[{$match:{}}],
         ... totalDocument: [{ $count: 'totalDocument' }]
      ... }
   ... }
... ]).pretty();

Sau đây là đầu ra hiển thị số lượng tài liệu -

Đầu ra

{
   "Alldata" : [
      {
         "_id" : ObjectId("5c76e6701e9c5dd6f1f78274"),
         "InstructorId" : 100,
         "InstructorName" : "Larry",
         "InstructorFavouriteSubject" : [
            "Java",
            "MongoDB",
            "Python"
         ]
      },
      {
         "_id" : ObjectId("5c76e69c1e9c5dd6f1f78275"),
         "InstructorId" : 200,
         "InstructorName" : "Sam",
         "InstructorFavouriteSubject" : [
            "SQL Server",
            "C#",
            "Javascript"
         ]
      }
   ],
   "totalDocument" : [
      {
         "totalDocument" : 2
      }
   ]
}