在 MongoDB 的现代版本中,最有效的方法是将新字段简单地标记为数组。这是 MongoDB 3.2 允许的:
db.collection.aggregate([
{ "$project": {
"names": [ "$senderName", "$receiverName" ]
}}
])
使用 MongoDB 2.6 中引入的 $map 运算符可能是最简单的方法。它转换数组,这就是你基本上要做的事情:
db.collection.aggregate([
{ "$project": {
"names": { "$map": {
"input": { "$literal": ["first","last"] },
"as": "el",
"in": { "$cond": [
{ "$eq": [ "$$el", "first" ] },
"$senderName",
"$receiverName"
]}
}}
}}
])
或者,您可以对不支持运算符但效率不高的早期版本执行类似的过程:
db.collection.aggregate([
{ "$project": {
"senderName": 1,
"receiverName": 1,
"type": { "$const": [ "first", "last" ] }
}},
{ "$unwind": "$type" },
{ "$group": {
"_id": "$_id",
"names": { "$push": { "$cond": [
{ "$eq": [ "$type", "first" ] },
"$senderName",
"$receiverName"
]}}
}}
])
但是,由于在任何一种情况下,您都没有真正聚合任何内容,因此通过您的语言自己支持的操作在客户端代码中使用类似的 map 方法是一个公平的论点。但是,如果您需要在聚合的某个阶段使用它,那么您必须这样做。
你仍然可以这样做,就是这样。