如何计算嵌入式mongodb php? [英] how to count of embedded mongodb php?

查看:48
本文介绍了如何计算嵌入式mongodb php?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 php 和 MongoDB 的问题.这是我的文档:

I've the problem with php and MongoDB. Here's my document:

"_id" : ObjectId("58d7815f387e76880c000000"),
"receiver" : "Katty",
"chat" : [
                {
                        "sender" : "jhon",
                        "date" : ISODate("2017-03-26T08:53:55Z"),
                        "message" : "Who are you?"
                        "status" : "sent"
                },
                {
                         "sender" : "jhon",
                        "date" : ISODate("2017-03-26T08:53:55Z"),
                        "message" : "What do you want?"
                        "status" : "pending"
                }
                {
                         "sender" : "jhon",
                        "date" : ISODate("2017-03-26T08:53:55Z"),
                        "message" : "Hah ?"
                        "status" : "pending"
                }
]

这是我的 php 程序:

And here's my php program:

<?php
$conn = new Mongo();
$db = $conn->selectDB('basarnas');
$query = $db->informasi_bencana;
$nosql = array("_id"=> new MongoId($id), "chat.status"=>"pending");
$result = $query->find($nosql);
$beritasar = $result->count();
$total = $beritasar;
echo "status pending = ".$total;
?>

结果是

status pending = 1

我想要的结果是

status pending = 2

当嵌入文档的状态为 "pending" 时如何计数?

How to count of embedded document when it has status = "pending" ?

推荐答案

您可以展开嵌入的文档,然后匹配状态,然后使用 groupby 计数所有文档.

You can unwind the embedded document and then match the status then using groupby count all the documents.

db.collection.aggregate([

                        { "$unwind": "$chat"},
                       {$match:{"chat.status": "pending"}}, 
                        { "$group":{"_id":null, count: {$sum:1}}}
                ])

简化获取所有文档并计算数组长度

Simplify fetch all the documents and count the length of the array

db.collection.aggregate([

                        { "$unwind": "$chat"},
                       {$match:{"chat.status": "pending"}}, 

                ])

这篇关于如何计算嵌入式mongodb php?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆