How to return array of string with mongodb aggregation

The .aggregate() method always returns Objects no matter what you do and that cannot change.

For your purpose you are probably better off using .distinct() instead, which does just return an array of the distinct values:

db.users.distinct("emails.address");

Which is exactly your desired output:

["[email protected]","[email protected]","[email protected]"]

If you really want to use .aggregate() then the tranformation to just the values needs to happen “outside” of the expression in post processing. And you should also be using $unwind when dealing with arrays like this.

You can do this with JavaScript .map() for example:

db.users.aggregate([
    { "$unwind": "$emails" },
    { "$group": { "_id": "$emails.address" } }
]).map(function(el) { return el._id })

Which gives the same output, but the .map() does the transformation client side instead of on the server.

Leave a Comment