2013-04-18 10 views
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 } 

回答

2

有相當多的創造性的方法來解決這個問題。使用concat @Sammaye是其中之一。但它只能從MongoDB 2.4開始提供。

我使用$ifNull

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

這工作做了一個。

但是,您可能已經注意到這是一個常見的功能,並且已經在此JIRA中提出了要求。

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

+0

非常好的邏輯...專爲別的東西而設計,但用於其他東西非常有效:-) 謝謝.. –

+0

這是很好的要注意這是比concat多一點的工作,它有效地爲每行添加了if語句,但這是一個很好的技巧 – Sammaye

+0

@Sammaye你是對的。它更像是一種黑客 –

相關問題