MongoDB 2.6引入了
$map
运算符,它是一个数组转换运算符,可用于实现以下功能:
db.phones.aggregate([
{ "$project": {
"phones": { "$map": {
"input": { "$literal": ["fax","cellphone"] },
"as": "el",
"in": {
"type": "$$el",
"number": { "$cond": [
{ "$eq": [ "$$el", "fax" ] },
"$fax",
"$cellphone"
]}
}
}}
}}
])
现在您的文档看起来正是您想要的样子。当然,诀窍是创建一个新数组,其中包含“传真”和“手机”的成员,然后通过匹配这些值使用新文档字段转换该数组。
当然,您也可以在早期版本中使用 $unwind
和 $group
以类似的方式执行此操作,但效率不如此高:
db.phones.aggregate([
{ "$project": {
"type": { "$const": ["fax","cellphone"] },
"fax": 1,
"cellphone": 1
}},
{ "$unwind": "$type" },
{ "$group": {
"_id": "_id",
"phones": { "$push": {
"type": "$type",
"number": { "$cond": [
{ "$eq": [ "$type", "fax" ] },
"$fax",
"$cellphone"
]}
}}
}}
])
当然,可以争论一下,如果你没有进行任何聚合操作,那么最好在代码中后处理集合结果。但这是另一种方法。
$group
阶段是不可能的。 - BatScream$project
阶段无法很好地将字段值投影到数组值中,请参见 SERVER-8141。 - wdberkeley$map
可以转换数组。 - Neil Lunn