MongoDB query for set of different categories

Viewed 1053

My Mongo database has a field which holds an array of strings, as follows:

db.band.insertMany([
   { name: "Alice", instrument: ["guitar", "voice"] },
   { name: "Bob", instrument: ["bass"] },
   { name: "Eve", instrument: ["drums", "voice"] }
]);

I would like to query the database to find the set of different instruments that can be played by the band members (in this example: ["guitar", "voice", "bass", "drums"]).

Is it possible to do this with a simple query? I haven't been able to find anything related to this.

1 Answers

You can use $unwind to get document per instrument and then $group with $addToSet to get unique values from all the documents:

db.band.aggregate([
    {
        $unwind: "$instrument"
    },
    {
        $group: {
            _id: null,
            instruments: { $addToSet: "$instrument" }
        }
    }
])

outputs:

{
    "_id": null,
    "instruments": [
        "drums",
        "bass",
        "voice",
        "guitar"
    ]
}
Related