我在MongoDB中有收藏:
{ "_id" : ObjectId("4d2407265ff08824e3000001"), "subida" : 3.95 }
{ "_id" : ObjectId("4d2551b4ae9fa739640df821"), "subida" : 6.03 }
{ "_id" : ObjectId("4d255b115ff08821c2000001"), "subida" : 5.53 }
{ "_id" : ObjectId("4d25e8d55ff08814f8000001"), "subida" : 1.96 }
Run Code Online (Sandbox Code Playgroud)
如何"subida"在所有文档中总结密钥的值?有了上面的文件,我应该收到以下内容:
{ "subida" : 17.47 }
Run Code Online (Sandbox Code Playgroud) 我有MongoDB Page和Post集合.每个页面文档都有字段postIds,它是post Ids(String对象)的数组.我想使用聚合来计算每个页面的帖子数(=数组postIds中的元素数).我编写了Mongo Shell聚合函数,它返回了我想要的内容:
db.page.aggregate([
{$unwind : '$postIds'},
{$group : {_id: '$_id', 'sum': { $sum: 1}}}
])
Run Code Online (Sandbox Code Playgroud)
并返回此结果:
{ "_id" : "3", "sum" : 3 }
{ "_id" : "2", "sum" : 3 }
Run Code Online (Sandbox Code Playgroud)
这意味着id为3的页面有3个帖子,id为2的页面也有3个帖子,这是正确的.
现在我想用Spring MongoDB Aggregation编写相同的代码,并编写了这个简单的JUnit测试:
/**
* Test page posts count
*/
@Test
public void testPagePostsCount() throws Exception{
MongoTemplate template = repository.getMongoTemplate();
Page page = new Page();
page.setPageId("2210");
page.setUserId("azec");
List<String> postList = new ArrayList<String>();
postList.add("53eb1a560efbe048c7ea698d");
postList.add("53eb1a6b0efbe048c7ea698e");
page.setPostIds(postList);
template.save(page);
Aggregation agg = newAggregation(
match(Criteria.where("pageId").is("2210")),
unwind("postIds"),
group("_id").sum("1").as("sum")
//project("$sum").and("pageId").previousOperation()
); …Run Code Online (Sandbox Code Playgroud)