简体   繁体   中英

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?

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" }
         }
      }
   ]
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM