Use $mergeObjects inside ReplaceRoot pipeline stag

2019-07-15 03:49发布

问题:

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