Home > OS >  mongodb - query to count number of array elements inside an object
mongodb - query to count number of array elements inside an object

Time:08-06

I've a mongodb collection "customer_vehicle_details" as below:

{
    "_id": ObjectId("5660c2a5b6fcba2d47baa2d9"),
    "customer_id": 4,
    "customer_vehicles": {
        "cars": [
            {
                "id": 1,
                "name": "abc"
            },
            {
                "id": 2,
                "name": "xyz"
            }
        ],
        "bikes": [
            {
                "id": 1,
                "name": "pqr"
            },
            {
                "id": 2,
                "name": "asdf"
            }
        ]
    }
}

I want to count total number of "cars" and total number of "bikes" separately in "customer_vehicles" collections. Not a sum of cars and bikes.

I tried with

db.customer_vehicle_details.aggregate(
   {
        $group: {
            _id: "$customer_vehicles.cars",
            total: { $sum: { $size:"$cars" } }
        }
   }
)

but this is giving me an error ""errmsg" : "The argument to $size must be an array, but was of type: missing"

How do I count total number of array elements inside an object in mongoDB?

CodePudding user response:

Does this helps:

db.collection.aggregate([
  {
    "$project": {
      carsCount: {
        "$size": "$customer_vehicles.cars"
      },
      bikesCount: {
        "$size": "$customer_vehicles.bikes"
      }
    }
  }
])

Here's the playground link.

  • Related