mongo聚合: - 使用Spring推送所有字段

时间:2018-01-04 18:56:38

标签: spring mongodb spring-mongo spring-mongodb

如果我有一系列书籍: -

{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
}    

组方法如下所示: -

 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在这里为空?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

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

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