2

I h

{
  code : "X1",
  elements : ["A", "B", "C", "D"]
},
{
  code : "X2",
  elements : ["C", "D"]
},
{
  code : "X3",
  elements : ["A"]
}
...

I would like to know the number of documents present for each type of value in the "elements" array. es. es.

"A" : 2
"B" : 1
"C" : 2
"D" : 2

is it possible with a single query?

1 Answer 1

4

You can $unwind your array to get single document per element and then run $group to count elements:

db.collection.aggregate([
    {
        $unwind: "$elements"
    },
    {
        $group: {
            _id: "$elements",
            count: { $sum: 1 }
        }
    }
])

EDIT: you can use additional group with $replaceRoot and $arrayToObject to return your ids as keys and counts as values:

db.collection.aggregate([
    {
        $unwind: "$elements"
    },
    {
        $group: {
            _id: "$elements",
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: null,
            counts: { $push: { k: "$_id", v: "$count" } }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$counts" }
        }
    }
])

Mongo Playground

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.