Mongo db:以 .map .join 方式转换字段
Mongo db: transform a field in a .map .join fashion
这是一个样本集合:
[
{
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 的新手。我尝试了一些构造,例如 $project、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"
]
}
这是一个样本集合:
[
{
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 的新手。我尝试了一些构造,例如 $project、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"
]
}