首页 > 解决方案 > 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 中构建我的代码?

标签: javamongodb

解决方案


试试这个:

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"))));
        }
    };
);

推荐阅读