Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You would have to use aggregate() with a double $unwind, like this:</p> <pre><code>db.test.aggregate([ // filter for documents with x=1 // note: this will use an index, if defined on "nested_documents.x" //{ $match: { "nested_documents.x": 1 } }, // reduce data to nested_documents, as other fields are not considered { $project: { nested_documents: 1 } }, // flatten the outer array { $unwind: "$nested_documents" }, // filter for nested_documents with x=1 // note that at this point nested_documents is no longer an array //{ $match: { "nested_documents.x": 1 } }, // flatten the inner array { $unwind: "$nested_documents.info" }, // filter for nested_documents.info.name = "sachin" // note that at this point nested_documents.info is no longer an array { $match: { "nested_documents.info.name": "sachin" } }, // format output: re-create inner array { $group: { _id: { id: "$_id", nested_documents: { x: "$nested_documents.x", y: "$nested_documents.y" } }, info: { $push: "$nested_documents.info" } } }, { $project: { "nested_documents.x": "$_id.nested_documents.x", "nested_documents.y": "$_id.nested_documents.y", "nested_documents.info": "$info" } }, // format output: re-create outer array { $group: { _id: "$_id.id", nested_documents: { $push: "$nested_documents" } } }, ]) </code></pre> <p>note: I put in as //comments the logic to filter for x=1 as you had in a previous example</p> <p>and the result is:</p> <pre><code>{ "result" : [ { "_id" : ObjectId("515d873457a0887a97cc8d19"), "nested_documents" : [ { "x" : 4, "y" : 3, "info" : [ { "name" : "sachin", "value" : "test" }, { "name" : "sachin", "value" : "test" } ] }, { "x" : 1, "y" : 2, "info" : [ { "name" : "sachin", "value" : "test" }, { "name" : "sachin", "value" : "test" } ] } ] } ], "ok" : 1 } </code></pre> <p>For more information on aggregate, refer to <a href="http://docs.mongodb.org/manual/applications/aggregation/" rel="nofollow">http://docs.mongodb.org/manual/applications/aggregation/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload