2015-06-10 41 views
0

朋友我遇到過基於用戶標識查找用戶的問題。我的用戶ID是long形式,我使用此代碼獲取用戶如何使用java標準查詢在mongodb中根據其ID來查找用戶?

Query query = new Query(Criteria.where("user.$id").is(userId));  
     User user = mongoTemplate.findOne(query, User.class); 

,我使用計數器設置ID,同時節省用戶,以便在DB我的收藏是這種形式

db.users.find().pretty() 
{ 
    "_id" : NumberLong(1), 
    "_class" : "com.domain.user.User", 
    "age" : 20, 
    "username" : "[email protected]", 
    "roles" : [ 
     "ROLE_USER" 
    ], 
    "firstName" : "abc", 
    "lastName" : "xyz", 
    "email" : "[email protected]", 
    "gender" : "male", 
    "isAccountLocked" : false, 
    "prefAgeFrom" : 0, 
    "prefAgeTo" : 0, 
    "aboutMe" : "I like to meet new people", 
    "notificationNewMatch" : true, 
    "notificationMessage" : true, 
    "updatedDate" : ISODate("2015-06-08T07:30:45.878Z") 
} 

因此,在存儲在NumberLong(1)表單中的id的基礎上,我想獲得id = 1的用戶。 在當前的scenerio中,我正在根據上面提到的id獲取用戶null。 我的主要要求是我想基於用戶獲取令牌。我的令牌以這種形式存儲在數據庫中

db.authenticationToken.find().pretty() 
{ 
    "_id" : NumberLong(4), 
    "_class" : "com.domain.user.AuthenticationToken", 
    "token" : "6db92ee4-2c23-42ee-985e-08af8e3d4f58", 
    "updatedDate" : ISODate("2015-06-10T04:47:34.434Z"), 
    "user" : DBRef("users", NumberLong(1)) 
} 

任何人都可以幫助我!

+0

使用'BasicDBObject'基礎你嘗試過在令牌? – Yogesh

+0

不,我不能用上面的代碼嗎? – Qasim

+0

不應該是'$ _id'嗎?您似乎在集合的名稱前面添加了名稱,您不需要這樣做 –

回答

0

做了我的問題,我終於得到了解決一些研究,我們可以發現用戶ID這樣

Query query = new Query(Criteria.where("user").is(userId)) 
    mongoTemplate.findOne(query,AuthenticationToken.class); 
相關問題