1

I know how to write a query such that I can count the number of items in an array per document using $size.

db.collection.aggregate(
   {project : {"name" : 1, _id:0, sizeOf : {$size : "$People.Age"}}}
)

How do I write a query using $size, but I only want to count the field if it equals a certain value (for example People.Ages.Current_Age : 21). I'm assuming I'd use $eq for that?

Sample Code:

{
    "People" : [
        {
            "Name" : "Jen",
            "Ages" : {
                "Current_Age" : 32,
                "Graduate_Age" : 26,
            }
        },
        {
            "Name" : "Bill",
            "Ages" : {
                "Current_Age" : 30,
                "Graduate_Age" : 22,
            }
        },
        {
            "Name" : "Josh",
            "Ages" : {
                "Current_Age" : 27,
                "Graduate_Age" : 24,
            }
        }
    ]
}
0

2 Answers 2

1

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "name": 1, "_id": 0,
    "sizeOf": {
      "$size": {
        "$filter": {
          "input": "$People",
          "as": "people",
          "cond": { "$eq": ["$$people.Ages.Current_Age", 21] }
        }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

6 Comments

What is the meaning of the dollar sign when used for "$People" and "$$people.age", I understand why it is used for operators but not other things.
$ represents the document fields and the $$ represents the let variables which we assume in the query.
Here in the above query. We have taken your $People documents array as input parameter of the $filter and taken $$people as let variable which contains single element from the array. It is same as javascript filter. Something like People.filter((people) => people.age === 21)
So what if Age (call it ages) is an object itself that has a single element in it that I want to access? For example I want to access People.Ages.CurrentAge. How would that change the above code? If I want CurrentAge = 21.
Updated my answer
|
0

You can use filter operator here, filter the array before taking size.

db.collection.aggregate(
    {project : {"name" : 1, _id:0, sizeOf : {$size : {
        $filter: {
            input: "$People.Age",
            as: "age",
            cond: { $eq:[$$age, 21] }
        }
    }}}}
)

2 Comments

I'm getting $$age is not defined (same if I make it $age)
Can you add an example document with the question.

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.