Marco Martin
Marco Martin

Reputation: 185

Merge/ group string arrays into single array

I have a collection of document and one of the fields is an array of strings... I'll like to merge into a 1 single array: Example:

db.books.insertMany([
  { "_id" : 8751, "username":"jjj22j", "ids" : [
            "3789732893289",
            "4383989834939"
        ] },
  { "_id" : 8752, "username":"jj5jj", "ids" : [ "323332"] },
  { "_id" : 8754,"username":"jjj4j", "ids" : [
            "28282828829",
            "111111111"
        ] },
  { "_id" : 8755,"username":"jjj4j", "ids" : [
            "77777"
        ] },
  { "_id" : 8754,"username":"jjjj3", "ids" : [
        ] },
])

I'll like to get:

{"ids" : ["3789732893289","4383989834939","323332","28282828829","111111111","77777"]}

It's very simple but I cannot find the way to do this.....

So far I've done:

db.users.aggregate([
        {
            $sort: 
                {
                    "_id":-1
                }
        },      
{
    $match: {
        "$and":[
            {ids : {$ne : null }},
            {username : {$ne : 'my_user'  }}
            ]},
},
{ $group : { "_id": null, ids: { $push: "$ids" } } },

]);

which the group part is NOT working....

Thanks for your help!

Upvotes: 1

Views: 585

Answers (2)

Gibbs
Gibbs

Reputation: 22964

Alternatively, you can use reduce with setUnion

{
  $project: {
    "ids": {
      "$reduce": {
        "input": "$ids",
        "initialValue": [
          
        ],
        "in": {
          "$setUnion": [
            "$$value",
            "$$this"
          ]
        }
      }
    }
  }
}

As per your expected output, you don't need sort.

Upvotes: 0

turivishal
turivishal

Reputation: 36104

  • Add $unwind stage before $gorup stage to deconstruct ids array,
  • Suggestion: swap $match and $sort stage, $sort is more efficient after filtered documents
db.users.aggregate([
    { 
        $match: {
            $and: [
                { ids : { $ne : null } },
                { username : { $ne : 'my_user' } }
            ]
        }
    },
    { $sort: { "_id": -1 } },
    { $unwind: "$ids" },
    { $group : { "_id": null, ids: { $push: "$ids" } } },
])

Upvotes: 2

Related Questions