问题
Dear All,
We have started using mongodb for our internal project. I am facing some issues and need your help.
Here is my table... books_issued
user_id book_id
1 1
1 3
2 5
2 8
I want to list it using the $group and result should be like this...
user_id book_id
1 1,3
2 5,8
We are using $match and $group. Please help to solve the same using java api.
Thanks,
Op
回答1:
This query uses the user_id as _id field for the aggregate and adds the book_id to the books array:
db.books_issued.aggregate( {$group: { _id: "$user_id", books: {$push: "$book_id"} } } )
The java code could look like:
DBObject groupObj = new BasicDBObject().append("$group",
new BasicDBObject().append("_id", "$user_id")
.append("books", new BasicDBObject("$push", "$book_id")));
List<DBObject> pipeline = new ArrayList<DBObject>();
pipeline.add(groupObj);
AggregationOutput r = books.aggregate(pipeline);
来源:https://stackoverflow.com/questions/24410424/mongodb-replacement-for-group-concat-in-mysql