>我有文章和标签集合。文章包含标签,这是对象ID数组。我也想获取 tagName,所以我展开(这给了我多行 - 每个标签数组条目 1 行)=> 查找(与选项卡集合连接)=>组(将其合并到原始结果集中)
我的 mongodb 查询如下,它给了我正确的结果:
db.articles.aggregate([
{"$unwind": "$tags"},
{
"$lookup": {
"localField": "tags",
"from": "tags",
"foreignField": "_id",
"as": "materialTags"
}
},
{
"$group": {
"_id": "$_id",
"title": {"$first": "$title"},
"materialTags": {"$push": "$materialTags"}
}
}
])
我相应的弹簧代码:
UnwindOperation unwindOperation = Aggregation.unwind("tags");
LookupOperation lookupOperation1 = LookupOperation.newLookup()
.from("tags")
.localField("tags")
.foreignField("_id")
.as("materialTags");
//I also want to add group operation but unable to find the proper syntax ??.
Aggregation aggregation = Aggregation.newAggregation(unwindOperation,
lookupOperation1, ??groupOperation?? );
AggregationResults<Article> resultList
= mongoTemplate.aggregate(aggregation, "articles", Article.class);
我试图玩弄团体操作,但没有太多运气。如何根据原始查询添加组操作?
提前谢谢。
Spring 中的组查询语法
{
"$group": {
"_id": "$_id",
"title": {"$first": "$title"},
"materialTags": {"$push": "$materialTags"}
}
}
是
Aggregation.group("_id").first("title").as("title").push("materialTags").as("materialTags")
最终查询
UnwindOperation unwindOperation = Aggregation.unwind("tags");
LookupOperation lookupOperation1 = LookupOperation.newLookup()
.from("tags")
.localField("tags")
.foreignField("_id")
.as("materialTags");
Aggregation aggregation = Aggregation.newAggregation(unwindOperation,
lookupOperation1, Aggregation.group("_id").first("title").as("title").push("materialTags").as("materialTags") );
AggregationResults<Article> resultList
= mongoTemplate.aggregate(aggregation, "articles", Article.class);
要获取更多信息,请浏览以下参考资料
http://www.baeldung.com/spring-data-mongodb-projections-aggregations
春季数据蒙戈布集团
从MongoDb聚合查询创建春季数据聚合
https://www.javacodegeeks.com/2016/04/data-aggregation-spring-data-mongodb-spring-boot.html