2

In my mongodb collection, I have sometimes two, sometimes one and sometimes null arrays on a document. Now I'd like to get one array over the whole collection with the values of these arrays.

The document looks like this:

{
    "title" : "myDocument",
    "listOne" : [ 
        "valueOne", 
        "valueTwo"
    ],
    "listTwo" : [ 
        "abc", 
        "qwer"
    ]
},
{
    "title" : "myDocumentTwo",
    "listTwo" : [  
        "321"
    ]
},
{
    "title" : "myDocumentAlpha",
    "listOne" : [ 
        "alpha", 
        "beta"
    ]
},
{
    "title" : "myDocumentbeta"
}

And I expect the following output:

"combinedList" : [
    "valueOne", 
    "valueTwo",
    "abc",
    "qwer",
    "321",
    "alpha",
    "beta"
]

It's like every possible value from these twos array out of every document in this collection.

2
  • "It's like every possible value from these twos array out of every document in this collection." Can you update your post to show that and what should be the final result? Right now you are only showing one document. Commented Jun 30, 2020 at 11:03
  • I updated it. The final result is an array with every possible value out of the other arrays. Commented Jun 30, 2020 at 11:10

1 Answer 1

2

You can do this using aggregate and $concatArrays

db.collection.aggregate([
  {
    $project: {
      combinedList: {
        $concatArrays: [{$ifNull: ["$listOne", []]}, {$ifNull: ["$listTwo", []]}]
      }
    }
  },
  { $unwind: "$combinedList" },
  { $group: { _id: null, combinedList: { $addToSet: "$combinedList"}}},
  { $project: { _id: 0, combinedList: 1 }}
])
Sign up to request clarification or add additional context in comments.

2 Comments

if the same value is in listOne and listTwo, is it possible to filter the combindedList that it's only displayed once?
That should be already working as we are using $group so you will always have distinct values in the combinedList

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.