2017-02-23 46 views
0

這裏變換一個字段是一個標本採集:蒙戈DB:在.MAP。加入時尚

[ 
{ 
    id: 1, 
    users: [ 
    {name: 'John Doe'}, {name: 'Ruth Paulson'} 
    ] 
}, 
{ 
    id: 2, 
    users: [ 
    {name: 'Meg Alosaurus'}, {name: 'Ruth Paulson'} 
    ] 
} 

] 

如何編寫一個查詢得到這樣的結果:

[ 
    { id: 1, usernames: ['John Doe', 'Ruth Paulson'] } 
    { id: 2, usernames: ['Meg Alosaurus', 'Ruth Paulson'] } 
] 

,或者:

[ 
    { id: 1, usernames: 'John Doe, Ruth Paulson'}, 
    { id: 2, usernames: 'Meg Alosaurus, Ruth Paulson'} 
] 

在JavaScript中,我會做:

collection.map(record => ({ 
    id: record.id, 
    usernames: record.map(user => user.name)/*.join(', ')*/ 
})); 

(注意:我對mongo db很新。我已經嘗試了一些構造,如$項目的MapReduce,$ CONCAT但無法得到我想要從他們的結果)

回答

1

下面是使用聚合查詢。

db.collection.aggregate([ 
    { $unwind: { path : "$users", preserveNullAndEmptyArrays : true }}, 
    {$group : {_id: "$_id", usernames : {$push : "$users.name"}}} 
]); 

輸出: -

/* 1 */ 
{ 
    "_id" : 2, 
    "usernames" : [ 
     "Meg Alosaurus", 
     "Ruth Paulson" 
    ] 
} 

/* 2 */ 
{ 
    "_id" : 1, 
    "usernames" : [ 
     "John Doe", 
     "Ruth Paulson" 
    ] 
}