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

tom10271
  • 4,222
  • 5
  • 33
  • 62
  • Seems to me you can utilize [this question's](http://stackoverflow.com/questions/16174591/mongo-count-the-number-of-word-occurences-in-a-set-of-documents) answers to your needs (with some changes ofcourse). It uses [MapReduce](https://docs.mongodb.com/manual/core/map-reduce/). – OzW May 13 '16 at 08: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](https://docs.mongodb.com/manual/reference/operator/aggregation/sum/) operator to count the instances – iestync May 13 '16 at 08:59
  • what kind of document is expected as an output? – profesor79 May 13 '16 at 09:10

1 Answers1

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
}
profesor79
  • 9,213
  • 3
  • 31
  • 52