J.Olufsen
J.Olufsen

Reputation: 13915

How to count items in nested array of mongo document using spring data?

I have to count the number of properties my Product has. I am using following document structure:

{
    "_id": ObjectId("0000000000000000000002"),
    "name" : "Test",
    "properties" : [

        ObjectId("0000000000000000000003"),
        ObjectId("0000000000000000000004")

          ]
}

How to do it?

Update:

My try:

...
@Autowired
    private MongoOperations mongoOperations;
...
mongoOperations.aggregate(
                new BasicQuery("{$match: {\"_id\" : " + new ObjectId(productId) + "}}," +
                        "{$unwind: \"$properties\"}," +
                        "{$project: {count:{$add:1}}}," +
                        "{$group: {_id: null, number: {$sum: \"$count\" }}} "),
                        Product.class);

I am getting error from IDE:

aggregate in MaongoOperations cannot be applied to or.springframework.data.mongodb.core.query.BasicQuery

How to fix it? Is it the easiest way to count properties using Sparing data?

Upvotes: 2

Views: 1538

Answers (1)

Anand Jayabalan
Anand Jayabalan

Reputation: 12904

If you are using MongoDB version 2.6 or later, you can make user of the $size aggregation operator to get the array size:

db.products.aggregate(
   [
      {
         $project: {
            name: 1,
            numberOfProperties: { $size: "$properties" }
         }
      }
   ]
)

Upvotes: 1

Related Questions