gpt4 book ai didi

mongodb - Spring Data MongoDB聚合场景

转载 作者:可可西里 更新时间:2023-11-01 10:29:02 26 4
gpt4 key购买 nike

如何翻译

$group : {
_id : 1 ,
likes : { $avg: { $size: ["$likes"] }},
count: { $sum: 1 },
}

进入 spring-data-mongodb 聚合查询?

最佳答案

您可以使用以下代码:

ArrayList<String> list = new ArrayList<>();
list.add("$likes");

BasicDBObject idObj = new BasicDBObject("_id", 1);
BasicDBObject likesObj = new BasicDBObject("$avg", new BasicDBObject("$size", list));
BasicDBObject countObj = new BasicDBObject("$sum", 1);

idObj.append("likes", likesObj).append("count", countObj);
BasicDBObject group = new BasicDBObject("$group", idObj);


List<DBObject> pipeline = new ArrayList<>();
pipeline.add(group);

MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient(), "dbname");
AggregationOutput aggregationOutput = mongoTemplate.getCollection("collectionName")
.aggregate(pipeline);
List<DBObject> dbObjects = (List<DBObject>) aggregationOutput.results();

//convert dbObjects into appropriate output

关于mongodb - Spring Data MongoDB聚合场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29769720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com