MongoDB的替代品在MySQL GROUP_CONCAT(Mongodb replacement

2019-10-20 08:04发布

亲爱的大家,

我们已经开始使用MongoDB的为我们的内部项目。 我面临着一些问题,需要你的帮助。

这里是我的表... books_issued

USER_ID book_id
1 1
1 3
2 5
2 8

我想用$组列出它,结果应该是这样的...
USER_ID book_id
1 1,3
2 5,8

我们使用$匹配和$组。 请帮助解决同使用的Java API。

谢谢,

Answer 1:

此查询使用USER_ID作为骨料_id领域,并增加了book_id的书籍数组:

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 replacement for GROUP_CONCAT in mysql