2016-03-28 238 views
0

讓我們假設我有一個具有以下結構的集合;獲取一個數組中的所有數組元素mongodb + node.js

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

我想讓一個數組中的所有學生元素。

我可以做:

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

這將返回我一個數組;

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

但是我想result = ['1', '2', '3', '11', '22','33'];

什麼是最有效的方式得到的結果就是這樣的?

+0

'變種合併= result.reduce(功能(A,B){ 返回a.students.concat(b.students); });' – Rayon

+2

@RayonDabre上述評論非常有資格成爲答案。 –

+0

@Reddy,我的猜測是OP正在尋找一些傳統的'mongo方式'來獲得預期的結果.. – Rayon

回答

2

如果你想要去的JavaScript的方式,使用Array.prototype.reduce

reduce()方法適用的功能對蓄電池和數組中的每個值(從左到右)將其減少到單個值。

試試這個:

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

0

可以使用aggragation框架:

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

嘗試用聚合框架。

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

這將發出:

{ 
    "result" : [ 
     { 
      "students" : [ 
       "1", 
       "2", 
       "3" 
      ] 
     }, 
     { 
      "students" : [ 
       "11", 
       "22", 
       "33" 
      ] 
     } 
    ] 
} 
相關問題