dph87312 2012-11-16 11:12 采纳率: 100%
浏览 116
已采纳

在MongoDB中计数

i've this query in SQL:

"SELECT code, name, count(*) FROM table WHERE customer = "XXX" GROUP BY code ORDER BY count(*) DESC;

I'm working with PHP, and I've to translate this SQL query for mongodb. I know that I've to do something like this for counting in mongodb:

$array_where_condition = array("customer" => "XXX");
$db->find($array_where_condition)->count();

but I can't understand how to write a query like the one above.

  • 写回答

3条回答 默认 最新

  • dongpao9165 2012-11-16 12:06
    关注

    If you are looking to use map reduce for such a query then you are already doing it wrong.

    MR would not be a performant replacement to the SQL aggregation framework in this case and would not run realtime inline to your own application.

    You can however use the aggregation framework, this might provide the performance you are looking for. I am a little rusty with the aggregation framework and this is written quickly however this might be something close to what you need:

    db.col.aggregate(
        {$match: {customer: XXX}}, 
        {$group: 
            {_id: "$code", name: "$name", count: {$sum: 1}}
        }
    )
    

    Here is the reference: http://docs.mongodb.org/manual/reference/aggregation/

    Of course the most performant and easiest way to sovle this problem is to design your schema in a NoSQL manner to avoid these sorts of queries: http://www.mongodb.org/display/DOCS/Schema+Design I have no idea of your current schema but it might not be NoSQL orientated if your looking to do a query like that frequently.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号