考虑我想要显示以下文件:
{
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"AuthorName": "dave",
"VirtualField" : "hardcoded_Value"
}
存储在MongoDB中的实际文档
{
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"author": "dave",
"score" : 80
}
我可以这样做:
collection.aggregate([
{ $project: {
_id: 1,
"AuthorName": "$author",
"VirtualField": "hardcoded_Value"
}
}
], function (err, doc) {
if (err) return console.error(err);
console.dir(doc);
}
);
有人能说出如何做同样的事吗?
注意:检索文档后我不想这样做。
<小时/> 得到错误:
[MongoError: exception: field path references must be prefixed with a '$' ('hardcoded_Value ]
name: 'MongoError',
errmsg: 'exception: field path references must be prefixed with a \'$\' (\'hardcoded_Value\'',
code: 15982,
ok: 0 }
<小时/> 使用时出现以下错误:
"VirtualField": {$concat: ["hardcoded_Value"]}
{ [MongoError: exception: invalid operator '$concat']
name: 'MongoError',
errmsg: 'exception: invalid operator \'$concat\'',
code: 15999,
ok: 0 }
答案 0 :(得分:6)
您应该在concat
使用"VirtualField": {$concat: ["hardcoded_Value"]}
:http://docs.mongodb.org/manual/reference/aggregation/#exp._S_concat
像这样:
{{1}}
答案 1 :(得分:2)
有很多创造性的方法可以解决这个问题。
使用来自@Sammaye的concat
是一个。但它只能从MongoDB 2.4开始提供。
我使用$ifNull
"VirtualField": {$ifNull: [null,"hardcoded_Value"]}
有效。
然而,您可能已经注意到这是一个常见功能,并已在此JIRA中提出过要求。