有 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构建代码


共 (1) 个答案

  1. # 1 楼答案

    试试这个:

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

    Spring数据

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