Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Aggregation group without _id mongo spring

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...