java - java中的MongoDb组
问题描述
我是 mongoDB 的新手,我不知道如何开始。我想按一个共同的值对我的数据库中的一些文档进行分组。在这里我留下一个例子:
{_id: 1, tag1: 1; tag2: 2}
{_id: 2, tag1: 3; tag2: 4}
{_id: 3, tag1: 2; tag2: 5}
{_id: 4, tag1: 1; tag2: 6}
{_id: 5, tag1: 1; tag2: 7}
如您所见,我在 tag1 中有一些共同点;我想将以下内容分组:
{_id: "valueoftag1", values:{_id: 1, tag2: 2}, {_id: 4, tag2: 6}, {_id: 5, tag2:7}}
或多或少。如何在 Java 中构建我的代码?
解决方案
试试这个:
db.collection.aggregate([
{
$group: {
_id: "$tag1",
values: {
$push: {
_id: "$_id",
tag2: "$tag2"
}
}
}
}
])
MongoDB 驱动程序
mongoCollection.aggregate(Arrays.asList(
new Document("$group", new Document("_id", "$tag1")
.append("values", new Document("$push", new Document("_id", "$_id").append("tag2", "$tag2"))))));
弹簧数据
Aggregation agg = Aggregation.newAggregation(
new AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext context) {
return new Document("$group", new Document("_id", "$tag1")
.append("values", new Document("$push", new Document("_id", "$_id").append("tag2", "$tag2"))));
}
};
);
推荐阅读
- c++ - cmake:find_package 用于架构
- php - ErrorException (E_NOTICE) 未定义变量:actualLabels
- python - QuickFix Python 插件 - 测试用例 - 分段错误错误
- c# - listview xamarin中项目的不同位置
- webstorm - Tailwind + WebStorm:“规则中的未知 CSS”
- react-native - 错误正则表达式无效:Metro Bundler 进程以代码 1 退出
- neo4j - 如何避免 Neo4j 密码查询中的循环
- angular - 角度 *ngIf 条件
- c# - С# 表单按钮不更新;当它们更新时
- python - 在特定位置使用 pdfrw 将图像插入可填充的 pdf