2

考虑我想显示以下文档:

   {
     "_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 }
4

2 回答 2

6

你应该concat在这里使用:http: //docs.mongodb.org/manual/reference/aggregation/#exp._S_concat

像这样:

"VirtualField": {$concat: ["hardcoded_Value"]}
于 2013-04-18T14:23:08.143 回答
2

有很多创造性的方法可以解决这个问题。

concat从@Sammaye使用就是其中之一。但它只能从 MongoDB 2.4 开始使用。

我做了一个使用$ifNull

    "VirtualField": {$ifNull: [null,"hardcoded_Value"]}

这样可行。

但是,您可能已经注意到这是一个常见功能,并且已在此 JIRA 中请求。

https://jira.mongodb.org/browse/SERVER-5991

于 2013-04-29T07:07:40.563 回答