2

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?

1 Answer 1

1

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" }
         }
      }
   ]
)
Sign up to request clarification or add additional context in comments.

2 Comments

Can you provide working Java code sample making use of Spring data?
What version of MongoDB are you using? I can provide Java code sample, but I haven't used Spring Data yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.