0

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?

3
  • You can use the $size array operator to get the number of elements in an array - use it in the $addFields or $project stage. And, you can use $add to sum the two array sizes. Commented Aug 5, 2022 at 3:00
  • @prasad_ I want to count total number of cars and bikes separately. Not a sum of cars and bikes. Commented Aug 5, 2022 at 3:09
  • $size: "$customer_vehicles.cars" - returns the number of elements in the cars array. Note the $size is an aggregate operator. Commented Aug 5, 2022 at 3:27

1 Answer 1

1

Does this helps:

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

Here's the playground link.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.