Use $mergeObjects inside ReplaceRoot pipeline stage in Spring MongoDB

早过忘川 提交于 2019-12-24 03:44:22

问题


i'm looking to reproduce this snipet into Java code :

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" }])

I'm here so far :

 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);

I've got an issue on the following point : {$replaceRoot: { newRoot: { $mergeObjects: [ "$arrayForeignObject", "$$ROOT" ] } } I can't succeed to make a mergeObjects. With this following java snippet, the AggregationOperation outcome is :

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

When i execute this java snippet, i end up with the new collection having only the foreign array inside and an _id field.

Does anyone faced this already and could give a hand please? Frigg0


回答1:


You have couple of issues here. Use 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);

For lower versions of 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);


来源:https://stackoverflow.com/questions/52593944/use-mergeobjects-inside-replaceroot-pipeline-stage-in-spring-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!