i am using Mongodb in Spring Web. And use MongoRepository to CRUD
I had: Collection: User
Later, i had to create a Group. because i shouldn't and can't embedded User into Group. I create new collection as SQL name: GroupUser. In here, i use:
@Field("groupId")
private String groupId;
@DBRef
private User user;
this will help to query list user in Group (query data and auto get User's content)
But as i want to get the list User's Id. Normally, in SQL we can do like:
select user.id from GroupUser where groupId = ?1
So i found that we can reduce and just get the select field like
@Query(value = "{ 'groupId' : ?0 }", fields = "{ '_id': 0, 'user.$id':1 }")
List<String> findAllUserIdByGroupId(String groupId);
but the result is JSON like:
{Object :{ User: {$id: "ObjectID in Hexa"} } }
~> So if i want to get list of ObjectId, i have to make a map or for loop to convert it. ~> It is not good at all
So i try to find out more solution:
This question give me an idea to create new return model.
db.getCollection('groupuser').aggregate([ { $project : { _id:0 , "newId" : "$user" }} ])
this newID can link to $user
but if i change it to get UserId $user.$id
~> this will give an error.
So just in mongo command, i can't get what i want like SQL did.
Please give me other solution for this.