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:
- match uid first
- sort the result by _id desc
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.