我正在使用MongoDB 3.2并试图找出是否有办法将多个字段组合成一个数组字段。例如,假设我有一个如下所示的查询:
db.companies.find({},
{
_id: 0,
CompanyName: 1,
CompanyAlias1: 1,
CompanyAlias2: 1,
CompanyAlias3: 1,
CompanyAlias4: 1
}).limit(4);
以上查询返回以下文档:
{ "CompanyName" : "Company ABC", "CompanyAlias1" : "Company ABC, Inc." }
{ "CompanyName" : "ACME Corp.", "CompanyAlias1" : "ACME Corporation", "CompanyAlias2" : "Coyote Lawncare" }
{ "CompanyName" : "Green Tea Sippers" }
{ "CompanyName" : "JS Inc", "CompanyAlias1" : "John Smith Ent", "CompanyAlias2" : "DBA J Smith", "CompanyAlias3" : "Mr. J Tree Climbing", "CompanyAlias4" : "Another crazy name", "CompanyAlias5" : "last one" }
相反,我希望将枚举的CompanyAlias [x]字段组合成一个名为CompanyAliases的数组。所以结果应该是这样的:
{ "CompanyName" : "Company ABC", "CompanyAliases" : [{ "Alias" : "Company ABC, Inc."} ]}
{ "CompanyName" : "ACME Corp.", "CompanyAliases" : [{ "Alias" : "ACME Corporation"}, { "Alias" : "Coyote Lawncare"} ]}
{ "CompanyName" : "Green Tea Sippers" }
{ "CompanyName" : "JS Inc", "CompanyAliases" : [{"Alias" : "John Smith Ent"}, {"Alias" : "DBA J Smith"}, {"Alias" : "Mr. J Tree Climbing"}, {"Alias" : "Another crazy name"}, {"Alias" : "last one"}]}
我是MongoDB的新手,来自RDBMS世界,我仍然围绕着它的许多概念。关于如何实现上述示例的任何见解都非常感谢!
答案 0 :(得分:0)
如果您知道最大别名的数量,可以明确地执行:
db.companies.aggregate([
{
$group: {
_id: {
_id: '$_id',
CompanyName: '$CompanyName'
},
CompanyAlias1: {
$push: {
Alias: '$CompanyAlias1'
}
},
CompanyAlias2: {
$push: {
Alias: '$CompanyAlias2'
}
},
CompanyAlias3: {
$push: {
Alias: '$CompanyAlias3'
}
},
CompanyAlias4: {
$push: {
Alias: '$CompanyAlias4'
}
},
CompanyAlias5: {
$push: {
Alias: '$CompanyAlias5'
}
}
}
},
{
$project: {
_id: 0,
CompanyName: '$_id.CompanyName',
CompanyAliases: {
$setUnion: ['$CompanyAlias1', '$CompanyAlias2', '$CompanyAlias3', '$CompanyAlias4', '$CompanyAlias5']
}
}
},
{
$project: {
CompanyName: 1,
CompanyAliases: {
$filter: {
input: '$CompanyAliases',
as: 'alias',
cond: {
$ne: ['$$alias', {}]
}
}
}
}
}
])