MongoDB在MySQL中替换GROUP_CONCAT [英] Mongodb replacement for GROUP_CONCAT in mysql
问题描述
亲爱的,
我们已经开始在内部项目中使用mongodb.我遇到了一些问题,需要您的帮助.
Dear All,
We have started using mongodb for our internal project. I am facing some issues and need your help.
这是我的桌子... bookings_issued
Here is my table... books_issued
user_id book_id
1                 1个
1                 3
2                 5
2                 8
user_id book_id
1 1
1 3
2 5
2 8
我想使用$ group列出它,结果应该是这样的...
user_id book_id
1 1,3
2 5,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
我们正在使用$ match和$ group.请帮助使用Java api解决相同问题.
We are using $match and $group. Please help to solve the same using java api.
谢谢,
推荐答案
此查询使用user_id作为聚合的_id字段,并将book_id添加到books数组:
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"} } } )
java代码如下:
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);
这篇关于MongoDB在MySQL中替换GROUP_CONCAT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!