Home > Blockchain >  How to Get the size of the filtered array in Mongodb
How to Get the size of the filtered array in Mongodb

Time:10-13

db.FlaggedData.aggregate([
{
    "$match": {
        "_id": "d86d6b48-e949-4daa-8364-9ef008416ae8"
    }
},
{
    "$project": {
        "users": {
            "$slice": [
                {
                    "$filter": {
                        "input": "$users",
                        "as": "users",
                        "cond": {
                            "$and": [
                                { SOME FILTERS
                                }
                            ]
                        }
                    } 
                },
                0,
                100
            ]
        },
        "count": {"$size": "$users"}
    }
    
}

])

How do I get the size of the filtered results?

as what I'm doing now I'm getting the size of the Array, not the size of the filtered result.

thanks.

CodePudding user response:

  • You need to put entire $slice into count.
db.collection.aggregate([
  {
    "$match": {
      "_id": "d86d6b48-e949-4daa-8364-9ef008416ae8"
    }
  },
  {
    "$project": {
      "users": {
        "$slice": [
          {
            "$filter": {
              "input": "$users",
              "as": "user",
              "cond": {
                "$and": [
                  {
                    $eq: [
                      "$$user.name",
                      "123"
                    ]
                  }
                ]
              }
            }
          },
          0,
          100
        ]
      },
      "count": {
        "$size": {
          "$slice": [
            {
              "$filter": {
                "input": "$users",
                "as": "user",
                "cond": {
                  "$and": [
                    {
                      $eq: [
                        "$$user.name",
                        "123"
                      ]
                    }
                  ]
                }
              }
            },
            0,
            100
          ]
        }
      }
    }
  }
])

mongoplayground

OR

  • Use two project
db.collection.aggregate([
  {
    "$match": {
      "_id": "d86d6b48-e949-4daa-8364-9ef008416ae8"
    }
  },
  {
    "$project": {
      "users": {
        "$slice": [
          {
            "$filter": {
              "input": "$users",
              "as": "user",
              "cond": {
                "$and": [
                  {
                    $eq: [
                      "$$user.name",
                      "123"
                    ]
                  }
                ]
              }
            }
          },
          0,
          100
        ]
      }
    }
  },
  {
    "$project": {
      users: {
        "$size": "$users"
      }
    }
  }
])

mongoplayground

  • Related