Find Nested Documents in Top-Level Array

I am trying to find all Documents/objects which contain false as one of their field’s values.

The Collection in question has a single Document:

{
  _id: 758ab35de3a258foo,
  Arr: [
    { str: "I am txt", bool: true },
    { str: "I am txt", bool: false},
    ...
  ]
}

Using collection.find() I have only been able to return the entire Document instead of returning only the Documents inside of the Arr array.

I have tried:

 collection.find({ "Arr.bool": false }
 collection.find({ "Arr": { $elemMatch: {"bool": false} }
 collection.find({ "Arr": { 
    $elemMatch: { 
      $ne: { "bool": true }
    }
  }     

So my questions are:

  1. Is this the best structure/model I should be using for this Collection? [There will probably only be a few more Documents added]

  2. Is it possible to get the results I am looking for using collection.find() alone, or is it necessary to filter/map the results I am getting afterwards?

Thank you for your time, and to anyone willing to help!! I really do appreciate it <3

Both queries are the same for match single field in an array and yes this will return the entire document because this is the match query part, it can not filter results in an array.

When you see $elemMatch documentation,

The $elemMatch operator limits the contents of an <array> field from the query results to contain only the first element matching the $elemMatch condition.

I am not sure what is the description of your project, but make sure The maximum BSON document size is 16 megabytes. as per this documentation,

  • yes it is possible in find() method from MongoDB 4.4, and yes it is necessary to filter/map the results in projection.

You can use aggregation projection operators in find() projection starting from MongoDB 4.4,

  • $filter to iterate loop of Arr array and filter by bool condition
collection.find(
  { "Arr.bool": false },
  {
    Arr: {
      $filter: {
        input: "$Arr",
        cond: { $ne: ["$$this.bool", true] }
      }
    }
  }
);
1 Like