【问题标题】:how to count with multiple criteria in mongo php如何在mongo php中使用多个条件进行计数
【发布时间】:2012-09-27 17:59:19
【问题描述】:

我是 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 数据库中有一个名为“coll”的集合,该集合中有一个名为“items”的字段,指向一个名为“title”的子文档

标签: php mongodb


【解决方案1】:

一个代码示例值一千字。看:

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

这是否回答了您的问题? :)

【讨论】:

  • 我可以在 mongo shell 中使用多个标准来计算,我对此没有问题。但是我怎样才能从 php 做同样的事情呢?另外,我选择使用链式方式是因为我听说 find().count() 和 count() 是一样的。
  • 这就是我想说的。使用find().count(),如果驱动程序被正确实现(我相信它是)应该不会受到惩罚。
【解决方案2】:

你必须先使用 find() 而不是 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

这是怎么做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多