此 count 指令用於計算集合中符合指定查詢的文件數量。 此指令有助於快速取得收藏中儲存的資料統計,例如符合特定條件的文件數量。
語法
指令 count 的語法如下:
db.collection.count(query, options)
-
query:一份使用查詢運算子指定選擇條件的文件。 -
options:隨意的。 一份指定選項的文件,例如limit和skip。
範例
以下是一些範例來示範該 count 指令的使用:
範例 1. 計算收藏中所有文件
統計館藏中 stores 所有文件:
db.stores.count({})
範例輸出
[mongos] StoreData> db.stores.countDocuments({})
60570
範例 2. 以特定標準計算文件
要計算擁有特定 _id 店鋪 ID 的店家數量:
db.stores.count({ "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" })
範例輸出
[mongos] StoreData> db.stores.count({ "_id": "e5767a9f-cd95-439c-9ec4-7ddc13d22926" })
1
範例 3. 以巢狀條件計算文件
要計算有特定促銷活動的店家數量:
db.stores.count({ "promotionEvents.eventName": "Incredible Discount Days" })
範例輸出
[mongos] StoreData> db.stores.count({ "promotionEvents.eventName": "Incredible Discount Days" })
2156
範例四。 多重標準的文件計數
計算特定緯度和經度的商店數量:
db.stores.count({ "location.lat": -2.4111, "location.lon": 72.1041 })
範例輸出
[mongos] StoreData> db.stores.count({ "location.lat": -2.4111, "location.lon": 72.1041 })
1
相關內容
- Review Migrating from MongoDB to Azure DocumentDB 的選項
- 閱讀更多關於 MongoDB 功能相容性的資訊