0

Let's assume I've collection which has the following structure;

{
  id:1,
  name: 'name1', 
  students: ['1', '2' , '3']
}
{
  id:2,
  name: 'name2', 
  students: ['11', '22' , '33']
}
...

I want to get all students element in one array.

I can do as:

db.collection.find({}, {students: 1, _id:0})

This returns me an array as;

result = [
   {students: ['1', '2', '3']},
   {students: ['11', '22','33']},   
]

However I want to get result = ['1', '2', '3', '11', '22','33'];

What is the most efficient way to get result just like this?

5
  • var merged = result.reduce(function(a, b) { return a.students.concat(b.students); }); Commented Mar 28, 2016 at 11:54
  • 2
    @RayonDabre the above comment very well qualifies to be an answer. Commented Mar 28, 2016 at 11:57
  • @Reddy, My guess is OP is looking for some conventional mongo way to get expected result.. Commented Mar 28, 2016 at 11:58
  • 1
    oh!! may be. But then he still has the javasccript tag on.. So you can go ahead with the answer. i dont see any prob Commented Mar 28, 2016 at 11:59
  • Try this db.collection.aggregate([ {$group: { $push: {$each: '$students'} }} ]); (I didn't test it) Commented Mar 28, 2016 at 12:03

3 Answers 3

2

If you want to go JavaScript way, Use Array.prototype.reduce

The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

Try this:

var result = [{
  students: ['1', '2', '3']
}, {
  students: ['11', '22', '33']
}, ];
var merged = result.reduce(function(a, b) {
  return a.students.concat(b.students);
});
console.log(merged);

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

Comments

0

You can use the aggragation framework:

db.collection.aggregate([{
    $unwind: '$students'
},{
    $group: {
        _id: '1',
        students: {
            $push: '$students'
        }
    }
}])

Comments

0

Try with aggregation framework.

db.collection.aggregate([
   {$project:{_id:0, students:1}},
   {$group:{_id:null, result:{$push:"$$ROOT"}}},
   {$project:{_id:0, result:1}}
])

This will emit:

{ 
    "result" : [
        {
            "students" : [
                "1", 
                "2", 
                "3"
            ]
        }, 
        {
            "students" : [
                "11", 
                "22", 
                "33"
            ]
        }
    ]
}

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.