仅显示文档中具有该匹配条件的子文档条目 - MongoDB

时间:2018-03-24 08:21:43

标签: mongodb mongodb-query aggregation-framework

让我们说这是数据(

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "ecf", score: 5 } ] } 
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xya", score: 7 } ] } 
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, { product: "xyz", score: 8 } ] }

我知道我可以像db.inventory.find( { "results.product": "xyz"} )那样进行查询,并获取与查询匹配的文档。 但我真正想要的是获得符合标准的子文档。

示例,我的查询应该只返回以下结果,而不是文档中的所有子文档。我们可以假设我想对单个文档执行此操作(我的意思是,在查询中明确应用_id: 3

{ _id: 3, results: [ { product: "xyz", score: 8 } ] }

更新 我从一些stackoverflow帖子中找到了一些答案,并基于此,我相应地修改了查询,这样的事情 - db.collection.find({'results.product': "xyz"}, {'results.$' : 1})这实际上只返回{​​{1}}字段中与标准匹配的1个子文档

我错过了什么!

更新2:

results

以上是https://docs.mongodb.com/manual/reference/operator/aggregation/redact/#examples

中示例的修改版本

如果我在{ _id: 1, title: "123 Department Report", tags: [ "G", "STLW" ], year: 2014, subsections: [ { subtitle: "Section 1: Overview", content: "Section 1: This is the content of section 1." }, { subtitle: "Section 2.a: Analysis", content: "Section 2: This is the content of section 2." }, { subtitle: "Section 2.b: Advanced Analysis", content: "Section 2: This is the content of section 2." }, { subtitle: "Section 3: Budgeting", content: "Section 3: This is the content of section3." } ] } 字段中查找analysis字,则查询应返回以下数据。

subsections.subtitle

0 个答案:

没有答案