我是Mongo的新手并且正在努力检索特定文档的特定子文档
鉴于以下集合,我想检索function (a, b) { return a + b; }
的内容。所以,我希望我的结果成为" Java"宾语。
"id" = 1 and "data.id" = 2
我正在执行{
"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",
}
]
}
之类的查询,但这会返回整个文档的ID为" 1"而不仅仅是我感兴趣的子文档。
我是否要求Mongo做一些不适合的事情,或者仅仅是我的语法有问题?
答案 0 :(得分:3)
也许这会有所帮助:
db.myCollection.find({"id":"1","data.id":"2"},{"id":1,"data.$":1})
不需要传递$和
答案 1 :(得分:2)
您可以使用聚合框架。
检索匹配"数据"的文档项目。
db.getCollection('yourColl').aggregate([
{$unwind:"$data"},
{$match:{"id":"1", "data.id":"2"}},
{$group:{_id:"$_id", "id":{$first:"$id"}, "title":{$first:"$title"}, "data":{$push:"$data"}}}
])
如果您只想获取特定的子文档
db.getCollection('yourColl').aggregate([
{$unwind:"$data"},
{$match:{"id":"1", "data.id":"2"}},
{$project:{_id:0, "id":"$data.id", "product":"$data.Product", "Description":"$data.Description"}}
])
答案 2 :(得分:1)
您可以将$ match与$ unwind结合使用。这两个是聚合框架的一部分。
您的问题的答案是:
db.collection.aggregate([{$unwind:'$data'},{$match:{'data.Product':{$eq:'Java'}}}]);
答案 3 :(得分:0)
回答了我自己的问题:
db.myCollection.find({$and : [{"id":"1"},{"data.id":"2"}]},{"data.$":1})