How to return a string array with mongodb aggregation

I need to return a string array with mongodb aggregation. I have done the following:

db.users.aggregate([{$group: {_id:"$emails.address"}}])

It returns:

{ "_id" : [ "a@a.com" ] }
{ "_id" : [ "b@a.com" ] }
{ "_id" : [ "c@a.com" ] }

Is there a way to return an array of string like this:

["a@a.com","b@a.com","c@a.com"]

Many thanks to everyone who is in no hurry to help me ..

EDIT

Adding data:

{
    "_id" : "ukn9MLo3hRYEpCCty",
    "createdAt" : ISODate("2015-10-24T03:52:11.960Z"),
    "emails" : [
        {
            "address" : "a@a.com",
            "verified" : false
        }
    ]
}
{
    "_id" : "5SXRXraariyhRQACe",
    "createdAt" : ISODate("2015-10-24T03:52:12.093Z"),
    "emails" : [
        {
            "address" : "b@a.com",
            "verified" : false
        }
    ]
}
{
    "_id" : "WMHWxeymY4ATWLXjz",
    "createdAt" : ISODate("2015-10-24T03:52:12.237Z"),
    "emails" : [
        {
            "address" : "c@a.com",
            "verified" : false
        }
    ]
}
+4
source share
2 answers

The method .aggregate()always returns Objectsno matter what you do and which cannot change.

For your purpose, you are probably better off using .distinct()instead, which returns an array of different values:

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

This is exactly what you need:

["a@a.com","b@a.com","c@a.com"]

.aggregate(), "" -. $unwind .

JavaScript .map(), :

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

, .map() , .

+8

.

.aggregate() , .

, .

, , node .

db.users.aggregate([
     { "$unwind": "$emails" },
     { "$group": { "_id": null, emails:{$push:"$emails.address"} } },
     { "$project":{emails:true,_id:false}}
 ])

:

{ "emails" : [ "a@a.com", "b@a.com", "c@a.com" ] }
+2

Source: https://habr.com/ru/post/1613740/


All Articles