【问题标题】:Use $mergeObjects inside ReplaceRoot pipeline stage in Spring MongoDB在 Spring MongoDB 的 ReplaceRoot 管道阶段使用 $mergeObjects
【发布时间】:2019-03-06 17:32:02
【问题描述】:

我希望将此片段复制到 Java 代码中:

db.getCollection('admins_comptes_client_ceov4').aggregate([
{$lookup: {from: "contrats_ceov4",localField: "CUSTOMERNUMBER",foreignField: "CUSTOMERNUMBER",as: "arrayForeignObject"}
{$unwind: { path: "$arrayForeignObject", preserveNullAndEmptyArrays: true}},
{$replaceRoot: { newRoot: { $mergeObjects: [ "$arrayForeignObject", "$$ROOT" ] } }},
{ $project: { "arrayForeignObject": 0, "_id": 0 } },
{ $out: "aggregate" }])

到目前为止我在这里:

 AggregationOperation lookup = Aggregation.lookup(fromCollection, localField, toMatchWith, "arrayForeignObject");
 AggregationOperation unwind = Aggregation.unwind("arrayForeignObject", true);
AggregationOperation replaceRoot = Aggregation.replaceRoot(Aggregation.ROOT);
AggregationOperation project = Aggregation.project("arrayForeignObject").andExclude("_id");
AggregationOperation out = Aggregation.out("aggregate");

Aggregation aggregation = Aggregation.newAggregation(lookup, replaceRoot, unwind, project, out);

mongoTemplate.aggregate(aggregation, initialCollection, AggregateModel.class);

我对以下几点有疑问: {$replaceRoot: { newRoot: { $mergeObjects: [ "$arrayForeignObject", "$$ROOT" ] } } 我无法成功创建合并对象。 使用以下 java sn-p,AggregationOperation 的结果是:

"$replaceRoot" : { "newRoot" : "$arrayForeignObject" } 

当我执行这个 java sn-p 时,我最终得到了一个新集合,里面只有一个外部数组和一个 _id 字段。

有没有人已经遇到过这个问题,可以帮忙吗? 弗里格0

【问题讨论】:

    标签: java mongodb aggregation-framework spring-mongodb


    【解决方案1】:

    这里有几个问题。使用 2.1.0 Release Spring Mongodb jar。

    AggregationOperation replaceRoot = Aggregation.replaceRoot().withValueOf(ObjectOperators.valueOf("arrayForeignObject").mergeWith(Aggregation.ROOT));
    AggregationOperation project = Aggregation.project().andExclude("_id", "arrayForeignObject");
    Aggregation aggregation = Aggregation.newAggregation(lookup, unwind, replaceRoot, project, out);
    

    对于spring mongodb的低版本

    AggregationOperation replaceRoot = ReplaceRootOperation.builder().withDocument("$mergeObjects", Arrays.asList("$arrayForeignObject", Aggregation.ROOT));
    AggregationOperation project = Aggregation.project().andExclude("_id", "arrayForeignObject");
    Aggregation aggregation = Aggregation.newAggregation(lookup, unwind, replaceRoot, project, out);
    

    【讨论】:

    • 因为我必须使用 org.springframework.dataspring-data-mongodb2.1.0.RELEASE version> 这个依赖破坏了我所有的 MongoTemplate 自动装配。我不明白为什么如果我拒绝这种依赖,我就没有问题。这是兼容性问题还是此依赖项无法在 Mongo Java Driver 3.8.2 中工作
    • 2.1.0 uses 3.8.2。所以我不确定你到底面临什么问题。我已经为其他版本添加了解决方法。
    • 没关系,我就是笨。如果使用 springframework 数据 2.1 还需要 2.1 spring 核心依赖。所以我已经能够测试你的建议。按预期工作非常感谢 Veeram
    • 嘿 Veeram,你能帮我解决这个问题吗? stackoverflow.com/questions/53213134/…
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多