如何在mongodb聚合$ project中创建像虚拟字段和硬编码值的东西?

Amo*_*rni 2 mongodb

考虑我想显示以下文档:

   {
     "_id" : ObjectId("512bc95fe835e68f199c8686"),
     "AuthorName": "dave", 
     "VirtualField" : "hardcoded_Value"
   }
Run Code Online (Sandbox Code Playgroud)

实际文档存储在MongoDB中

   {
     "_id" : ObjectId("512bc95fe835e68f199c8686"),
     "author": "dave",
     "score" : 80
   }
Run Code Online (Sandbox Code Playgroud)

我可以这样做:

collection.aggregate([
    { $project: {
        _id: 1,
        "AuthorName": "$author",
        "VirtualField": "hardcoded_Value"
       }
    }
    ], function (err, doc) {
        if (err) return console.error(err);
        console.dir(doc);
    }
);
Run Code Online (Sandbox Code Playgroud)

有谁能说出如何做同样的事情?

注意:检索文档后我不想这样做.


得到错误:

[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 }
Run Code Online (Sandbox Code Playgroud)


使用时出现以下错误: "VirtualField": {$concat: ["hardcoded_Value"]}

{ [MongoError: exception: invalid operator '$concat']
  name: 'MongoError',
  errmsg: 'exception: invalid operator \'$concat\'',
  code: 15999,
  ok: 0 }
Run Code Online (Sandbox Code Playgroud)

Sam*_*aye 6

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

像这样:

"VirtualField": {$concat: ["hardcoded_Value"]}
Run Code Online (Sandbox Code Playgroud)

  • @AmolMKulkarni看起来像concat仅从2.4开始提供.你的版本是什么? (2认同)