Spring mongodb - 展开后的组操作 - 找不到 $first 或 $push [英] Spring mongodb - group operation after unwind - can not find $first or $push
问题描述
我有文章&标签集合.文章包含作为 objectId 数组的标签.我也想获取 tagName,所以我展开(这给了我多行 - 每个标签数组条目 1 个)=> 查找(与选项卡集合连接)=> 组(将其合并到原始结果集)
I have articles & tags collection. Articles contain tags which is array of objectId. I want to fetch tagName as well, so I unwind (this gives me multiple rows - 1 per tag array entry) => lookup (joins with tabs collection) => group (combine it into original result set)
我的mongodb查询如下,结果正确:
My mongodb query is as follows, which gives me correct result:
db.articles.aggregate([
{"$unwind": "$tags"},
{
"$lookup": {
"localField": "tags",
"from": "tags",
"foreignField": "_id",
"as": "materialTags"
}
},
{
"$group": {
"_id": "$_id",
"title": {"$first": "$title"},
"materialTags": {"$push": "$materialTags"}
}
}
])
我对应的Spring代码:
My corresponding Spring code:
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);
我尝试玩组操作,但运气不佳.如何根据原始查询添加组操作?
I tried to play around with group operation but without much luck. How can I add group operations as per original query ?
提前致谢.
推荐答案
Spring for
Group query syntax in Spring for
{
"$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);
要获取更多信息,请浏览以下参考资料
To get more info please go thru the below references
http://www.baeldung.com/spring-data-mongodb-projections-aggregations
https://www.javacodegeeks.com/2016/04/data-aggregation-spring-data-mongodb-spring-boot.html
这篇关于Spring mongodb - 展开后的组操作 - 找不到 $first 或 $push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!