Dusted
Dusted

Reputation: 123

MongoDB Java Aggregation - addToSet Multiple Fields

I'm trying to run a MongoDB aggregation to retrieve distinct nested Documents in a single collection using the Java driver.

How can I add more than one field into the Java Accumulators.addToSet document output?

For instance in MongoDB Shell this works:

db.systems.aggregate([{$unwind:"$planets"},{$group:{_id:"$surfaceType", distinct:{$addToSet:{radius:"$planets.radius", surfaceType:"$planets.surfaceType"}}}}])

Output: planets:[{ "radius" : 10.0,"surfaceType" : "water"},{"radius":"100.0","surfaceType" : "rock"}, ...]

But in Java this does not work:

collection.aggregate(Arrays.asList(Aggregates.group("$surfaceType",Accumulators.addToSet("planets", {radius:"$planets.radius", surface:"$planets.surfaceType", ...}))));

Just dont quite understand the syntax required for the String Expression in addToSet.

Thanks

Upvotes: 1

Views: 4858

Answers (1)

chridam
chridam

Reputation: 103335

You can pass a document in the addToSet operator:

collection.aggregate(
    Arrays.asList(
       Aggregates.unwind("$planets", new UnwindOptions().preserveNullAndEmptyArrays(true)),
       Aggregates.group("$surfaceType",
            Accumulators.addToSet("planets", 
                new Document("radius", "$planets.radius")
                    .append("surfaceType", "$planets.surfaceType")
            )
        )
    )
);

Upvotes: 3

Related Questions