如何獲取 MongoDB 集合中檔案的數量?


以下是獲取 MongoDB 集合中檔案數量的語法

let anyVariableName= db.getCollection(‘yourCollectionName’);
yourVariableName.count();

讓我們首先建立一個包含檔案的集合

> 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")
}

以下是使用 find() 方法顯示某個集中所有檔案的查詢

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

這將產生以下輸出

{ "_id" : ObjectId("5c9a5e2015e86fd1496b38a1"), "CustomerName" : "Bob" }
{
   "_id" : ObjectId("5c9a5e3515e86fd1496b38a2"),
   "CustomerName" : "Ramit",
   "CustomerAge" : 23
}
{
   "_id" : ObjectId("5c9a5e4c15e86fd1496b38a3"),
   "CustomerName" : "Adam",
   "CustomerAge" : 27,
   "CustomerCountryName" : "US"
}

以下是獲取 MongoDB 集合中檔案數量的查詢,

> let myCollectionName = db.getCollection('countNumberOfDocumentsDemo');
> myCollectionName.count();

這將產生以下輸出

3

更新於: 30-Jul-2019

481 次瀏覽

啟動你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.