Aerondight
Aerondight

Reputation: 33

Mongodb find the latest of each group and implemented in Spring boot

I'm new to mongodb. Let's say I have documents in a collection:

  [
        {
          _id: ObjectId("1"),
          uid: "test",
          obj: Object
                    name: "a",
                    field1: "..."
        },

        {
          _id: ObjectId("2"),
          uid: "test",
          obj: Object
                    name: "a",
                    field1: "..."
        },
        {
          _id: ObjectId("3"),
          uid: "test",
          obj: Object
                    name: "b",
                    field1: "..."
        },
         {
          _id: ObjectId("4"),
          uid: "test2",
          obj: Object
                    name: "b",
                    field1: "..."
        }
    ]

I want to retrieve a list of obj with unique obj.name, expected output would be:

  [
      {
         _id: ObjectId("2") // not really necessary , just to show that the obj was under ObjectId("2")
         name: "a",
         field1: "..."
      },
      {
         _id: ObjectId("3") // not really necessary , just to show that the obj was under ObjectId("3")
         name: "b",
         field1: "..."
      }
    ]

My thought of achieving this:

  1. match uid first
  2. sort the result by _id desc
  3. group by obj.name

    [{ $match: { uid: "test" } }, { $sort: { _id: -1 } }, { $group: { _id: "$obj.name" } }]

What I got:

{
  _id:"a"
},
{
  _id:"b"
}

2nd question: How to do such query with Spring boot mongo template or other spring boot mongo library?

 Public class A {
       private String _id;
       private String uid;
       private Obj obj;
    }

    Public class Obj {
           private String name;
           private String field1;
    }

In Java sense, I want to retrieve List<Obj>

but have no idea how to do so.

Much appreciated for any help.

Upvotes: 2

Views: 1709

Answers (1)

Valijon
Valijon

Reputation: 13103

It's very simple. Follow the tutorial.

Add the below code:

//Add this code to your service class
@Autowired
private MongoTemplate mongoTemplate;

...

//Aggregation pipeline    
Aggregation agg = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("uid").is("test")),
    Aggregation.sort(Direction.DESC, "_id"),
    Aggregation.group("obj.name").first("obj").as("obj"),
    Aggregation.replaceRoot("obj")
);

AggregationResults<Obj> result = mongoTemplate.aggregate(agg, "collection", Obj.class).getMappedResults();
//result.forEach(System.out::println);

Upvotes: 1

Related Questions