1

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!

2 Answers 2

2
  • 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" } } },
])
Sign up to request clarification or add additional context in comments.

Comments

0

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.

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.