Lets say this is the data (
{ _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 } ] }
I understand that I can make queries like db.inventory.find( { "results.product": "xyz"} )
and get the documents that matches the query.
But what I really want is get the subdocuments that fit the criteria.
Example, MY query should return just the below result instead of all the subdocuments in the document. We can assume that i want to do this operation on a single document( i mean, applying _id: 3
explicitly in the query.
{ _id: 3, results: [ { product: "xyz", score: 8 } ] }
UPDATE:
I found some answer from some stackoverflow post and based on that, i modified the query accordingly, something like this - db.collection.find({'results.product': "xyz"}, {'results.$' : 1})
this is actually returning only 1 subdocument in results
field which matches the criteria
Am i missing something!
UPDATED 2:
{
_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."
}
]
}
the above is a modified version of the example from https://docs.mongodb.com/manual/reference/operator/aggregation/redact/#examples
the query should return the following data, assuming im looking for analysis
word in subsections.subtitle
field.
{
_id: 1,
title: "123 Department Report",
tags: [ "G", "STLW" ],
year: 2014,
subsections: [
{
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."
}
]
}