0

I have a JSON like this, I want to count by status false JSON img

{
  "chats": [
    {
      "memberId": "ff9e28ec-4f6f-42e2-9e66-43b888267fe5",
      "messages": [
        {
          "messagesId": "54174c03-c669-44fb-872a-75ff5c52166f",
          "user": {
            "userId": "4dd8495a-5704-435d-bee2-6b474e25cbbf",
            "name": "Event",
            "profilePicture": "png"
          },
          "createdAt": "",
          "title": "belajar",
          "image": "minio.png",
          "messages": "belajar",
          "status": false
        }
      ]
    }
  ]
}

I want to get the count of all messages where status is false.

Example

{
 "memberId" : "ff9e28ec-4f6f-42e2-9e66-43b888267fe5"
 "statusCount" : 2
}
3
  • 1
    Is not clear what you ask . Post you code attempt ... Commented Jul 7, 2019 at 20:58
  • Is this output of any DB query . ? Commented Jul 7, 2019 at 21:19
  • 2
    So, you want to count all elements in the messages array with a status of false? You can't do this with a normal query. You'll need to use the aggregation pipeline, using $unwind to get individual messages and then perform the count manually (e.g. use $group with the $sum operator). Commented Jul 7, 2019 at 21:55

2 Answers 2

1
db.getCollection('inbox').aggregate([
{ "$unwind": "$chats" },
{
  "$match": {
    "chats.messages.status": false
  }
},
{ "$unwind": "$chats.messages" },
{ "$group": { 
    "_id": "$chats.memberId",
    "count": { "$sum": 1 }
}}])

I try this query and the result is

{
"_id" : ObjectId("5d207957e887785f2c0c745e"),
"count" : 4.0
}

is that something that you want?

Sign up to request clarification or add additional context in comments.

2 Comments

nice,thanks a lot, im modified query like this and solve pastebin.com/RTqRJJ9k
nice to hear that. great works! seems like i have to workout about mongodb
1

solve query like this

db.inbox.aggregate([
{ $unwind: "$chats" },
{ $unwind: "$chats.messages" },
{
  $match: {
    "chats.messages.status": false
  }
},
{
    $group: {
        _id: { inboxId: "$inboxId", memberId: "$chats.memberId" },
            count: { $sum :1 }
        }
    },
    {
        $project : {inboxId : '$_id.inboxId', memberId : '$_id.memberId', count : '$count', _id : 0}

    }

])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.