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?
CodePudding user response:
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".