2010-11-05 73 views
1

我正在嘗試使用de> collection.count方法,但嘗試使用使用Ruby驅動程序的count()Mongodb功能(db.collection_name.count({data:value})。它不接受任何參數使用mongodb紅寶石驅動程序的參數計數操作

我檢查了collection.count()方法文檔,它只返回集合中對象的總量,其中無法將「filter」參數傳遞給此方法。

是否有可能使用COUNT()MongoDB的特性與濾波器參數在一些其他的方式?

回答

3

是否有可能以某種其他方式使用count()Mongodb特性和過濾器參數?

從貝(命令行),你可以做到以下幾點:

db.collection.find({ data : value}).count()

很明顯,你必須做的Ruby類似的東西,但它應該是相當簡單的。

+0

不,從shell我不需要使用find()然後count(),我可以使用count()和參數。 – razenha 2010-11-05 15:31:02

+0

我不想將所有數據拖到內存中以獲取給定查詢的對象數。 – razenha 2010-11-05 15:31:41

+0

好的,「.find()」方法只返回一個遊標,它不返回所有的數據。當您執行count()時,它應該循環遍歷數據,而不會實際加載數據並通過導線推送它。 – 2010-11-08 23:30:58

2

對於那些誰只是想使用Ruby驅動程序的答案:

# actual number of records 
DB["posts"].find({"author" => "john"}).to_a.length 
=> 48 
# *total* number of documents in the collection (the query matching is ignored) 
DB["posts"].count({"author" => "john"}) 
=> 1431 
# more efficient way (using the count server-side command) 
DB["posts"].find({"author" => "john"}).count 
=> 1431 
0

它實際上可以使用.count()當你在命令行上做,它只是記錄不完整。

蒙戈命令行:

db.User.find({"emails.5": {"$exists": true}}).count()

蒙戈Ruby驅動程序:

db.collection('User').count({:query => {"emails.5" => {"$exists" => true}}})

這個和其它.count()選項文件here