Im trying to make this operation in java:
db.product.aggregate([{
$match: { gtin: { $in: ["7890203", "7890204" ]}}}])
.group({
_id: "$gtin",
status: {$last: "$status"},
createdDate: {$last: "$createdDate"}
})
This return only the last document for given gtins. (Thats my goal).
The java code:
Criteria criteria = Criteria.where("gtin").in(gtinList);
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.group("_id", "gtin")
.last("status").as("status")
.last("createdDate").as("createdDate"));
mongoTemplate.aggregate(aggregation, "product", Product.class).getMappedResults();
It return all the documents for the given gtins (i want only the last one based on createdDate).
I tried another approach for group like this:
Aggregation.group(Fields.from(Fields.field("_id", "gtin")))
.last("status").as("status")
.last("createdDate").as("createdDate"));
But i got an exception :nested exception is java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [9788580414851]
Same if i take out "_id" from group.
Can anyone help me achieve this?
Thanks in advance.
Edit: sample documents
{
"_id": "5fc140b3f6cb564068997e7d",
"sideProductId": {
"value": "89545"
},
"createdDate": "2020-11-27T18:08:51.799Z",
"lastUpdatedDate": "2020-11-27T18:08:52.860Z",
"status": "CONCLUDED",
"direction": "SIDE1_SIDE3",
"gtin": "78902030",
"attempt": 1,
"_class": "product.Product"
}
The response from mongoaggregation after the query:
{
"_id": "78902030",
"status": "CONCLUDED",
"createdDate": "2020-11-27T18:08:50.121Z"
}
Edit 2:
Finally got it. @varman asked about the java class i was using.
Mongotemplate was mapping to the @document class, which has the _id as an ObjectId.
Had to create a new class to map it correctly with only the fields i want.
_id, status, createdDate, but _id as a String to map gtin to it.
question from:
https://stackoverflow.com/questions/65854981/aggregation-group-without-id-mongo-spring