Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring data mongo db计数具有特定条件的嵌套对象_Spring_Mongodb - Fatal编程技术网

Spring data mongo db计数具有特定条件的嵌套对象

Spring data mongo db计数具有特定条件的嵌套对象,spring,mongodb,Spring,Mongodb,我有这样一份文件: 'subject' : { 'name' :"...." 'facebookPosts':[ { date:"14/02/2017 20:20:03" , // it is a string text:"facebook post text here", other stuff here } ] } 我想计算日期字段中包含的特定对象中的facebookPosts,例如“23/07/2016” 现在,我通过提取客户端(spring)中的所有文档和计数来实

我有这样一份文件:

'subject' : {
'name' :"...."
'facebookPosts':[

 {
 date:"14/02/2017 20:20:03" , // it is a string
 text:"facebook post text here",
 other stuff here  

 }

]

}
我想计算日期字段中包含的特定对象中的facebookPosts,例如“23/07/2016”


现在,我通过提取客户端(spring)中的所有文档和计数来实现这一点,但我认为这并不高效。

您需要聚合结果

final Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("facebookPosts.date").regex(REGEX)),
                    Aggregation.unwind("facebookPosts"),
                    Aggregation.group().count().as("count"));
正则表达式可能不是最好的解决方案,只是一个例子

展开
将数组拆分为单独的元素,然后您可以进行计数

创建一个包含计数的类,类似于:

public class PostCount {
    private Long count;
    // getters, setters
}
然后像这样执行它:

AggregationResults<PostCount> postCount = mongoTemplate.aggregate(aggregation, Subject.class, PostCount.class);
long count = postCount.getMappedResults().get(0).getCount();
AggregationResults postCount=mongoTemplate.aggregate(聚合,Subject.class,postCount.class);
long count=postCount.getMappedResults().get(0.getCount();

是的,我发现这样做很有效,但如果我只想计算满足条件的facebook帖子,我的意思是我只想计算它们,而不需要获取它们并自己计算它们。mongoTemplate.count(查询、分类)它会计算主题或其中的facebook帖子吗?更新了答案,我没有正确阅读您的问题,很抱歉,这一行仍然有一个小问题PostCount PostCount=mongoTemplate.aggregate(aggregation,Subject.class,PostCount.class);它告诉我“无法从AggregationResult转换为PostCount”