2017-05-05 85 views
0

我收集的數據是這樣的:在貓鼬返回內部數據

{ 
"_id" : ObjectId("590ad1f747627f86e585a4af"), 
"code" : "IR", 
"name" : "Iran", 
"background" : "https://vfbdt" 
"topics" : [ 
    { 
     "name" : "overview", 
     "facts" : [ 
      { 
       "key" : "capital", 
       "value" : "Kuala Lumpur" 
      }, 
      { 
       "key" : "population", 
       "value" : "232424234" 
      }, 
      { 
       "key" : "reliogion", 
       "value" : "Islam" 
      } 
     ] 
    }, 
    { 
     "name" : "Good to know", 
     "facts" : [ 
      { 
       "key" : "key1", 
       "value" : "value1" 
      } 
     ] 
    } 
] 
} 

我想回到上名主題名稱代碼通過過濾器的所有事實。我寫這篇文章的代碼,但它不能正常工作,並將所有收集只是代碼過濾,並且不考慮topic.name

export function getFactsByCodeAndName(req, res, next) { 
Country.find({code:req.params.code,'topics.name':req.params.name}) 
.exec((err, facts) => { 
if (err) return next(err); 

return res.status(200).json({ 
    success: true, 
    message: 'Get country', 
    data: facts, 
    }); 
    }); 
} 
+0

它返回「全部收集」還是「全國文件」?假設以後,您可以在應用程序級別按名稱過濾主題。如果出於某種原因想要在數據庫級別執行此操作,則需要通過代碼使用[彙總框架](https://docs.mongodb.com/manual/aggregation/)到'$ match'國家,'$ unwind'主題,'$匹配'他們的名字,'$項目'必填字段。 –

回答

0

你應該在查詢中使用投影 -

國家。找到({代碼:req.params.code, 'topics.name':{$ elemMatch:{req.params.name}}})

這裏是文檔的鏈接 -

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

希望這會有所幫助。

+0

這看起來不像使用$ elemMatch給我的正確方法。文檔說「如果您在$ elemMatch表達式中僅指定一個條件,則不需要使用$ elemMatch。」另外我認爲elemMatch需要一個對象而不是一個字符串。 – tomtom