蒙戈DB:在.MAP。加入时尚
问题描述:
这里变换一个字段是一个标本采集:蒙戈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但无法得到我想要从他们的结果)
答
下面是使用聚合查询。
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"
]
}