CHRD
CHRD

Reputation: 1957

Query count of sub documents based on condition in Mongo DB

I have a collection where a sample document has the following shape:

{
  "document_1": {
    "field_1": {},
    "array_1": {
      "subobject_1": {
        "subobject_field_1": "true",
        "subobject_field_2": {},
        "subobject_field_3": {}
      },
      "subobject_2": {
        "subobject_field_1": "false",
        "subobject_field_2": {},
        "subobject_field_3": {}
      }
    }
  }
}

The number of subobjects (subobject_) under array_1 varies and is not the same for all documents. I am trying to make a query that, for each document, counts the number of subobjects where subobject_field_1 is true. I also want to be able to specify exactly which fields to return, and set additional conditions (in this case the additional condition would be that field_1 = "A"). In this case, the output would look like:

{
  "document_1": {
    "field_1": "A",
    "array_1": 1
  }
}

I have tried the code below, but that only gives me the number of subobjects regardless of whether or not subobject_field_1is trueor false.

db.getCollection('myCollection').aggregate([
{
    $match: {field_1: 'A'}
    },
{
    $project: {field_1: 1, array_1: {$size: $array_1}}
    }
])

Thanks in advance!

Upvotes: 1

Views: 904

Answers (1)

Ashh
Ashh

Reputation: 46441

You can use below aggregation

db.collection.aggregate([
  { "$match": { "field_1": "A" }},
  { "$addFields": {
    "field_2": {
      "$size": {
        "$filter": {
          "input": { "$objectToArray": "$field_2" },
          "cond": { "$eq": ["$$this.v.subdoc_field_1", "true"] }
        }
      }
    }
  }}
])

Upvotes: 2

Related Questions