0

Collection A have:

[
    {
        name: 'peter',
        types: ['human', 'male', 'young']
    },
    {
        name: 'mice',
        types: ['male', 'young']
    },
    {
        name: 'hen',
        types: ['female', 'old']
    }
]

I know how to get all distinct values of types but how to get its no. of appearance. How to extract it with Mongo query?

It would be great if you can show the solution in Doctrine QueryBuilder way.

Thanks

3
  • Seems to me you can utilize this question's answers to your needs (with some changes ofcourse). It uses MapReduce. Commented May 13, 2016 at 8:55
  • 1
    I'd try it with the aggregation framework, maybe start by unwinding the array and then using the group stage with a sum operator to count the instances Commented May 13, 2016 at 8:59
  • what kind of document is expected as an output? Commented May 13, 2016 at 9:10

1 Answer 1

2

with aggregation framework you can sum apperance of all array elements using query provide below:

db.collection.aggregate([{
            $project : {
                _id : 0,
                types : 1
            }
        }, {
            $unwind : "$types"
        }, {
            $group : {
                _id : "$types",
                count : {
                    $sum : 1
                }
            }
        }

    ])

and output:

{
    "_id" : "human",
    "count" : 1
}, {
    "_id" : "old",
    "count" : 1
}, {
    "_id" : "male",
    "count" : 2
}, {
    "_id" : "young",
    "count" : 2
}, {
    "_id" : "female",
    "count" : 1
}
Sign up to request clarification or add additional context in comments.

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.