user7141537
user7141537

Reputation:

Mongoose count documents where count of array elements with property set to false is less than a value

I have a collection where most of the documents have an array of objects, the property that I am concerned with is a boolean, and I am looking to get a count of total documents where the number of objects in the array have that property set to false, less than 10 times.

The schemas are something like this

let MatchSchema = new Schema({
  home: {
    squad: [ SquadSchema ]
  },
  away: {
    squad: [ SquadSchema ]
  },
});

let SquadSchema = new Schema({
  check: Boolean
});

I have been searching for a way to do this, and it looks like Aggregate is the way to go, though I am having trouble finding a solution. It looks like I can use this to get the size of each home.squad, away.squad, and the id for each document.

await Match.aggregate([
   {
      $project: {
         "squadCountHome": {$size: "$home.squad"},
         "squadCountAway": {$size: "$away.squad"},
      }
   }
]);

Can aggregate be used to see if the check value in squad is false less than 10 times, and more than 0?

Upvotes: 0

Views: 492

Answers (1)

user7141537
user7141537

Reputation:

Joe pointed me towards $filter, and I got my solution which looks little something like below.

$project and $filter retrieved all elements in squad.home, and squad.away where the check property was set to false. Then used $project and $size to get the total of elements with false values in both, and finally $match to identify if either home or away sizes are greater than 0, and less than 10

{
      $project: {
        home: {
          $filter: {
            input: "$home.squad",
            as: "home",
            cond: {$eq: ["$$home.check", false]}
          }
        },
        away: {
          $filter: {
            input: "$away.squad",
            as: "away",
            cond: {$eq: ["$$away.check", false]}
            },
          }
        }
      },
      {
        $project: {
          "squadCountHome": {$size: "$home"},
          "squadCountAway": {$size: "$away"}
        }
      },
      {
        $match: {
          $or: [ { squadCountHome: { $gt: 0, $lt: 10 } }, { squadCountAway: { $gt: 0, $lt: 10 } } ]
        }
      }
    ```

Upvotes: 0

Related Questions