0

I have a JavaScript code.

db.xxx.aggregate([
    {$project: {object:{$first:'$object.array'}, _id:0}}
])

I don't know how to overwrite it by java client.

import org.springframework.data.mongodb.core.MongoTemplate;
...
Aggregation.newAggregation(
    Aggregation.project().andExclude("_id").???
)

And where to find the usage?

1 Answer 1

1

This is TestDocument

public class TestArrayDocument {
    @Id
    String id;
    Integer[] x;
}

Inject MongoTemplate

@Autowired
MongoTemplate mongoTemplate;

This is aggregate method

  TypedAggregation<TestArrayDocument> aggregation  = Aggregation.newAggregation(TestArrayDocument.class,Aggregation
            .project()
            .andExclude("_id")
            .andExpression("first(x)").as("object"));

    List<Map> mapData=  mongoTemplate
            .aggregate(aggregation,Map.class)
            .getMappedResults();

x is your $object.array.

return in LinkedHashMap "object"=>"firstElement".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.