MongoDB $ addFields使用org.springframework.data.mongodb.core.MongoTemplate

问题描述 投票:0回答:1

我如何在Spring Data MongoDB Reactive中编写$addFields查询,以获得更简单,更复杂的字段添加,如下所示:

db.getCollection("mycollection").aggregate(
[
    { 
        "$addFields" : {
            "existingObjectField.newFieldArray" : [
                "$existingObjectField.existingFieldObject"
            ]
        }
    },
    { 
        "$addFields" : {
            "existingFieldArray" : {
                "$map" : {
                    "input" : "$existingFieldArray", 
                    "as" : "item", 
                    "in" : {
                        "existingFieldObject" : {
                            "_id" : "$$item. existingFieldObject._id",
                            "newFieldArray" : [
                                "$$item. existingFieldObject.existingFieldObject"
                            ]
                        }
                    }
                }
            }
        }
    },
    { 
        "$out" : "mycollection"
    }
]

);

在第一个添加字段中,我只是使用现有的一个对象字段创建一个新的数组字段。

在第二个添加字段中,执行相同但在文档中的数组中的对象内。

mongodb spring-data-mongodb
1个回答
2
投票

match/unwind一样,在spring data mongo中不存在AddFieldOperation但你可以编写自己的custom Aggregation类来为addFieldOpration添加调用方法,如下所示。

 public class AddFieldOperation implements AggregationOperation {

      private final Document document;

      /**
       * Creates a new {@link MatchOperation} for the given {@link CriteriaDefinition}.
       *
       * @param criteriaDefinition must not be {@literal null}.
       */
      public AddFieldOperation(final Document document) {

        Assert.notNull(document, "Criteria must not be null!");
        this.document = document;
      }

      /*
       * (non-Javadoc)
       *
       * @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.
       * springframework.data.mongodb.core.aggregation.AggregationOperationContext)
       */
      @Override
      public Document toDocument(final AggregationOperationContext context) {

        return new Document("$addFields", this.document);
      }
    }

现在制作CustomAggregation类。

public class CustomAggregation extends Aggregation {

  public static AddFieldOperation addField(final Document document) {

    return new AddFieldOperation(document);
  }
}

一切准备就绪你需要调用Addfield方法并传递Document对象示例中的所有查询: -

AddFieldOperation addField =
        CustomAggregation.addField(new Document().append("fieldName", fieldValue));

注意 Document类来自import package org.bson.Document; 这是一个文档表示为{@code Map}。 在spring data mongo中实现的所有聚合操作最终都转换为Document对象,这将在shell中执行。因此,如果某些聚合管道尚未在spirng data中实现,那么在这种情况下,我们可以自己编写并传递用mongo shell编写的查询,我们可以在Document对象中传递它。

© www.soinside.com 2019 - 2024. All rights reserved.