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

Categories

0 votes
3.5k 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.


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

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...