在Spring MongoDB中的ReplaceRoot管道阶段内使用$ mergeObjects

时间:2018-10-01 15:04:13

标签: java mongodb aggregation-framework spring-mongodb

我正在尝试将此片段复制为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" ] } } 我无法成功制作mergeObjects。 使用以下以下Java代码段,AggregationOperation结果为:

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

当我执行此Java代码段时,最终得到的新集合只有内部的外部数组和_id字段。

有人有没有遇到过这种情况,可以帮忙吗? Frigg0

1 个答案:

答案 0 :(得分:2)

您在这里遇到了几个问题。使用2.1.0发行版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);