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?
$sizearray operator to get the number of elements in an array - use it in the$addFieldsor$projectstage. And, you can use$addto sum the two array sizes.$size: "$customer_vehicles.cars"- returns the number of elements in the cars array. Note the$sizeis an aggregate operator.