首页 > 解决方案 > DocumentDb-spring-用其他字段值更新字段

问题描述

我正在使用 Spring 的 DocumentDb,我想在一个字段上使用另一个字段的值进行 updateMany。

以下查询在 MongoDb 控制台中运行:

 db.mtpProject.update({}, [{$set: {"fieldToBeUpdated": "$myCurrentField"}}]).

如果我删除 $set 之前的 [],则该字段不会使用 myCurrentField 的值更新,而是使用字符串“myCurrentField”更新。

在Java中,我尝试像这样执行它:

  MongoDatabase db = mongoTemplate.getDb();
  MongoCollection collection = db.getCollection("myProject");
  collection.updateMany(new Document(), new Document("$set", new 
  Document("fieldToBeUpdated", "$myCurrentField")));

但是因为在没有数组的情况下创建它,所以只是将 fieldToBeUpdated 的值设置为“$myCurrentField”。

我提到我也尝试使用带有 $out 的 $addFields,但 DocumentDb 不支持 $out。

 Aggregation agg =
                Aggregation.newAggregation(
                        aoc ->
                                new Document(
                                        "$addFields",
                                        new Document("fieldToBeUpdated", "$myCurrentField")),
                        aoc -> new Document("$out", "myProject"));

        mongoTemplate.aggregate(agg, "myProject", MyProject.class);

我希望使用保存在 myCurrentField 上的值而不是字段名称来更新字段。

标签: javaspringmongodbaggregation-frameworkaws-documentdb

解决方案


推荐阅读