Spring mongodb - 展开后的组操作 - 找不到 $first 或 $push [英] Spring mongodb - group operation after unwind - can not find $first or $push

查看:60
本文介绍了Spring mongodb - 展开后的组操作 - 找不到 $first 或 $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

spring 数据 mongodb group by

从 MongoDb 聚合查询创建 Spring 数据聚合

https://www.javacodegeeks.com/2016/04/data-aggregation-spring-data-mongodb-spring-boot.html

这篇关于Spring mongodb - 展开后的组操作 - 找不到 $first 或 $push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆