MongoRepository get only specific field as result

*爱你&永不变心* 提交于 2019-12-11 17:33:54

问题


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.

来源:https://stackoverflow.com/questions/55949195/mongorepository-get-only-specific-field-as-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!