Yigit Can
Yigit Can

Reputation: 361

Get all array elements in one array mongodb + node.js

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?

Upvotes: 0

Views: 284

Answers (3)

Rayon
Rayon

Reputation: 36609

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);

Upvotes: 2

Saleem
Saleem

Reputation: 8978

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"
            ]
        }
    ]
}

Upvotes: 0

BanksySan
BanksySan

Reputation: 28500

You can use the aggragation framework:

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

Upvotes: 0

Related Questions