2017-05-05 83 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