【发布时间】: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在这里为空?任何帮助将不胜感激
【问题讨论】:
-
感谢@Veeram +1。那肯定有帮助。已更新问题。你能看一下吗
-
是的,投影应该是
project("bookList").and("author", "_id") -
效果很好!希望这一切都能被接受为答案。非常感谢!
标签: spring mongodb spring-mongo spring-mongodb