【问题标题】:mongo aggregation:- push all fields using Springmongo 聚合:- 使用 Spring 推送所有字段
【发布时间】:2018-06-14 13:39:07
【问题描述】:

如果我有藏书:-

{author: "tolstoy", title:"war & peace", price:100, pages:800}
{author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}

如果我在按作者分组后想要这样的结果:-

{ author: "tolstoy",
   books: [
      {author: "tolstoy", title:"war & peace", price:100, pages:800}
      {author: "tolstoy", title:"Ivan Ilyich", price:50,  pages:100}
]
}

使用原始 mongo 查询,我可以执行以下操作:-

{$group: {
 _id: "$author",
 books:{$push: {author:"$author", title:"$title", price:"$price", pages:"$pages"}},
}}

但是我如何使用 spring 来做到这一点,我尝试了这样的事情:-

 private GroupOperation getGroupOperation() {
    return group("author").push("title").as("title").push("price").as("price").push("pages").as("pages");
}

but this does not seem to work. Any help would be appreciated.

更新:- 我使用了@Veeram 建议的链接中的解决方案,效果很好,但是我在投影时遇到了另一个问题。我的投影类看起来像:-

public class BookSummary{

private String author;

private List<Book> bookList;
  //all getters and setters below
}    

group 方法如下所示:-

 private GroupOperation getGroupOperation() {
    return group("author").push(new BasicDBObject("id","$_id").append("title","$title").append("pages","$pages").append("price","$price")).as("bookList");
}

投影方法如下:-

private ProjectionOperation getProjectOperation() {
    return project("author").and("bookList").as("bookList");
}

以及最终的聚合操作:-

mongoTemplate.aggregate(Aggregation.newAggregation(groupOperation,projectionOperation), Book.class, BookSummary.class).getMappedResults();

但是这给出了结果:-

[
{
    "author": null,
    "bookList": [
        {
            "id": null,
            "title": "title1",
            "pages": "100",
            "price":"some price"
        },
        {
            "id": null,
            "title": "title2",
            "pages": "200",
            "price":"some price"
        }
    ]
}
]

为什么作者和id在这里为空?任何帮助将不胜感激

【问题讨论】:

标签: spring mongodb spring-mongo spring-mongodb


【解决方案1】:

您应该在项目阶段使用_id 进行投影。

private ProjectionOperation getProjectOperation() {
    return project("_id").and("bookList").as("bookList");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多