Mongodb replacement for GROUP_CONCAT in mysql

一个人想着一个人 提交于 2019-12-11 09:19:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!