Sau đây là cú pháp để đếm số lượng tài liệu trong bộ sưu tập MongoDB
let anyVariableName= db.getCollection(‘yourCollectionName’); yourVariableName.count();
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.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a5e2015e86fd1496b38a1")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Ramit","CustomerAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a5e3515e86fd1496b38a2")
}
>db.countNumberOfDocumentsDemo.insertOne({"CustomerName":"Adam","CustomerAge":27,"CustomerCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9a5e4c15e86fd1496b38a3")
} 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.countNumberOfDocumentsDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" }
{
"_id" : ObjectId("5c9a5e3515e86fd1496b38a2"),
"CustomerName" : "Ramit",
"CustomerAge" : 23
}
{
"_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"),
"CustomerName" : "Adam",
"CustomerAge" : 27,
"CustomerCountryName" : "US"
} Sau đây là truy vấn để đếm số lượng tài liệu trong bộ sưu tập MongoDB,
> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo');
> myCollectionName.count(); Điều này sẽ tạo ra kết quả sau
3