2015-08-08 98 views
0

任何人都知道如何在javascript中僅匹配子文檔返回文檔?mongodb javascript:只有匹配子文檔的返回文檔

例如這裏是數據庫中的記錄:

[ 
    {"name":"bestbuy",notes:["article IT", "article 2"]}, 
    {"name":"microsoft",notes:["article IT", "another IT", "article 5"]}, 
    {"name":"IBM",notes:["article 8", "article 9"]} 
] 

這裏是我的查詢:

collection.find({"company.notes":/IT/}, function(err,result){}) 

結果是:

[ 
    {"name":"bestbuy",notes:["article IT", "article 2"]}, 
    {"name":"microsoft",notes:["article IT", "another IT", "article 5"]}, 
] 

但我預期的結果是:

[ 
    {"name":"bestbuy",notes:["article IT"]}, 
    {"name":"microsoft",notes:["article IT", "another IT"]} 
] 

任何想法? 感謝

+0

可能重複://計算器.COM /問題/ 3985214 /檢索,只有最查詢元素功能於一個對象陣列功能於MongoDB中收集) –

+0

感謝,更具體的JavaScript我認爲 – aaron

回答

1

可以使用聚合

db.collection.aggregate([ 
    {$match: {"notes": /IT/}}, 
    {$unwind: "$notes"}, 
    {$match: {notes: /IT/}}, 
    {$group: {_id: '$_id', name: {$first: '$name'}, notes: {$push: '$notes'}}}, 
    {$project: {'name': 1, 'notes': 1, _id: 0}} 
]) 

收率:

{ "name" : "microsoft", "notes" : [ "article IT", "another IT" ] } 
{ "name" : "bestbuy", "notes" : [ "article IT" ] } 
[只檢索MongoDB中集合的對象陣列中的查詢元件](HTTP的
+0

感謝,我沒有嘗試,因爲我發現數據庫模式是不同的,所以我更新了我的問題。你能否介紹一下? – aaron

+0

和另一個問題:爲什麼需要使用2個「$匹配」? – aaron

+0

@aaron這是第一個問題的答案。如果您的數據庫模式不同,請接受答案並**問**一個新問題。你不應該創建一個[cham​​eleon](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions)問題。 – styvane