0

如何将以下 MongoDB 操作写入 Java Springboot 代码?

db.collection.aggregate({
  "$group": {
    _id: {
      $trim: {
        input: "$name"
      }
    },
    doc: {
      "$first": "$$ROOT",
      
    }
  }
},
{
  "$replaceRoot": {
    "newRoot": "$doc"
  }
})
4

1 回答 1

0

希望您使用的是 mongo 模板。您可以使用 BSON 方法。转换 MONGO SHELL 查询的技巧

public List<Object> test() {

    Aggregation aggregation = Aggregation.newAggregation(      
        p-> new Document("$group",
                new Document("_id",
                    new Document("$trim",
                        new Document("input","$name")
                    )
                ).append("doc",
                    new Document("$first","$$ROOT")
                )
            ),
             replaceRoot("doc")
    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}

但你也可以试试这个。请确保这是有效的

public List<Object> test() {

    Aggregation.newAggregation(
        group("$_id".trim()).first("$$ROOT").as("doc"),
        replaceRoot("doc")
        )
    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();

}
于 2021-05-16T03:51:24.223 回答