如何在 MONGO PHP 中使用多个条件进行计数


how to count with multiple criteria in mongo php

我是mongodb的新手。我认为 mongo shell 和 php mongo 驱动程序之间存在一些用法差异。

我可以在 mongo shell 中使用多个标准进行计数。例如:

db.coll.count( { _id:ObjectId('4fb27b9c876b88e53d000000'), 
                 'items.title':'example' } );

但是我不能用 php mongo 驱动程序进行相同的计数。我试过这个,但它返回 0。

$coll->count( array('_id'=>new MongoID('4fb27b9c876b88e53d000000'), 
                    'items.title'=>'example' ) );

但是,如果我使用 find() 然后使用 count(),我会得到相同的计数结果:

$coll->find( array('_id'=>new MongoID('4fb27b9c876b88e53d000000'), 
                   'items.title'=>'example' ) ).count();

得到了我想要的,但我认为链接方式可能效率低下。我错了吗?

如何用多个标准进行计数?

一个代码示例胜过千言万语。看:

% mongo
MongoDB shell version: 2.1.1
connecting to: test
> db.foo.count
function (x) {
    return this.find(x).count();
}

这回答了你的问题吗?:)

你必须首先使用 find() 和 than count()

db.foo.count() -- will return 0, because db.foo it is only accessing the collection
db.foo.find($where).count() --- will return the number of documents in the collection

这是怎么做到的。