简体   繁体   English

如何使用Spring数据计算Mongo文档嵌套数组中的项目?

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

I have to count the number of properties my Product has. 我必须计算我的Product具有的properties数量。 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: 我从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? 这是使用Sparing数据计算属性的最简单方法吗?

If you are using MongoDB version 2.6 or later, you can make user of the $size aggregation operator to get the array size: 如果您使用的是MongoDB 2.6版或更高版本,则可以让$ size聚合运算符的用户获取数组大小:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用spring mongo data api更新嵌入式mongo文档 - How to update embedded mongo document using spring mongo data api 如何使用Spring Data Mongo DB对类进行建模,以存储具有不同字段和类型长度的嵌套JSON文档 - How to Model class using Spring Data Mongo DB to store nested JSON document with varying length of fields and type 如何使用Spring数据从Mongo中的数组文档字段中仅获取匹配结果 - How to Get Only Matched Result from An Array Field of Document in Mongo Using Spring Data Spring Mongo Upsert嵌套文档 - Spring Mongo Upsert nested document 在Spring Mongo中作为嵌套文档项目 - Project as nested document in spring mongo Spring Data Mongo @CreatedAt 注释不适用于嵌套文档字段 - Spring Data Mongo @CreatedAt annotation not working with nested document field 使用 Spring Data Mongo 在 mongodb 聚合中分组时如何获取具有非空数组字段的元素计数? - How to get the count of element with non-empty-array-field when group in mongodb aggregate using Spring Data Mongo? 如何更新 MongoDB 中的嵌套文档而不是使用 Spring Data Java - How update nested Document in MongoDB preferred of using Spring Data Java 如何使用spring data solr在solr中插入嵌套文档? - How to insert Nested document in solr using spring data solr? 如何使用Jongo将项目添加到Mongo数组? - How to add items to Mongo array using Jongo?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM