我必须计算properties
我的Product
的数量。我正在使用以下文档结构:
{
"_id": ObjectId("0000000000000000000002"),
"name" : "Test",
"properties" : [
ObjectId("0000000000000000000003"),
ObjectId("0000000000000000000004")
]
}
怎么做?
更新
我的尝试:
...
@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);
我从IDE收到错误:
aggregate in MaongoOperations cannot be applied to or.springframework.data.mongodb.core.query.BasicQuery
如何解决?这是使用Sparing数据计算属性的最简单方法吗?
答案 0 :(得分:0)
如果您使用的是MongoDB 2.6或更高版本,则可以让$size聚合运算符的用户获取数组大小:
db.products.aggregate(
[
{
$project: {
name: 1,
numberOfProperties: { $size: "$properties" }
}
}
]
)