5

Imagine I have this collection:

{
  id: 1,
  b: { 
   "field1": ['foo'],
   "field2": ['bar']
  }
}
{
  id: 2,
  b: { 
   "field2": ["foobar"],
   "field3": ["foofoo"]
  }
}

And I want to obtain a new collection with MongoDB:

{
 id: 1,
 b_grouped: ['foo', 'bar']
}
{
 id: 2,
 b_grouped: ["foobar", "foofoo"]
}

I don't know all the name of the fields in the documents, anyone would have an idea of how to perform something like this:

db.collection.aggregate(
   [
      { "$project": { "b_grouped": { $concatArrays: ["$b.*"] } } }
   ]
)
2
  • 1
    Your sample data is not valid JSON. Are these two documents or just one? Commented Oct 23, 2020 at 11:30
  • I got confused while writing it, I fixed it and it is actually two documents Commented Oct 23, 2020 at 12:09

1 Answer 1

10

You can try,

  • $reduce input b as a array after converting from object to array using $objectToArray, this will convert object in "k" (key), "v" (value) format array of object,
  • $concatArrays to concat initialValue ($$value) of $raduce and array of b object's field $$this.v
db.collection.aggregate([
  {
    $project: {
      b_grouped: {
        $reduce: {
          input: { $objectToArray: "$b" },
          initialValue: [],
          in: {
            $concatArrays: ["$$this.v", "$$value"]
          }
        }
      }
    }
  }
])

Playground

Sign up to request clarification or add additional context in comments.

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.