【发布时间】:2016-03-21 03:09:00
【问题描述】:
我是 Mongo 的新手,正在努力检索特定文档的特定子文档
给定以下集合,我想检索"id" = 1 and "data.id" = 2 所在的内容。所以,我希望我的结果是“Java”对象。
{
"id" : "1",
"title" : "Section1",
"data" : [
{
"id" : "1",
"Product" : "Scala",
"Description" : "",
},
{
"id" : "2",
"Product" : "Java",
"Description" : "",
},
{
"id" : "3",
"Product" : "Ruby",
"Description" : "",
},
{
"id" : "4",
"Product" : "HTML5",
"Description" : "",
}
]
}
{
"id" : "2",
"title" : "Section2",
"data" : [
{
"id" : "4",
"Product" : "Ansible",
"Description" : "a free software platform for configuring and managing computers",
},
{
"id" : "1",
"Product" : "Chef",
"Description" : "an open source configuration management tool",
},
{
"id" : "2",
"Product" : "Puppet",
"Description" : "an open-source tool for managing the configuration of computer systems",
},
{
"id" : "3",
"Product" : "Saltstack",
"Description" : "open source configuration management and remote execution application",
}
]
}
我正在执行类似db.myCollection.find({$and : [{"id":"1"},{"data.id":"2"}]}) 的查询,但这会返回整个文档,其 id 为“1”,而不仅仅是我感兴趣的子文档。
我是在要求 Mongo 做一些它不适合做的事情,还是只是我的语法有问题?
【问题讨论】:
-
为此,您需要使用投影。你可以在这里找到一些例子:docs.mongodb.org/v3.0/reference/operator/aggregation/project
标签: mongodb