今天在項目中遇到了關於MongoDB巢狀查詢,之前一直沒有接觸過,查詢了相關資料後將結果記錄下來。
MongoDB中的資料如下:
> db.customer.findOne(){ "_id" : ObjectId("57636c8e35defe029962107e"), "_class" : "com.bu2trip.ticket.model.Customer", "name" : "wang", "phone" : "18408221624", "gender" : 1, "birthday" : "1995-7-9", "passport" : "620524", "login_user" : { "_id" : ObjectId("5760e593086659036b77c124"), "email" : "test@bu2trip.com", "phone" : "110" }}
如果要查詢整個內嵌文檔,查詢語句如下:
db.customer.find({"login_user" : {"_id":ObjectId("5760e593086659036b77c124"), "email" : "test@bu2trip.com","phone" : "110"}})
在查詢條件中必須寫出以login_user為鍵的所有值。
只針對內嵌文檔的特定索引值進行查詢如下:
db.customer.findOne({"login_user.phone":"110"})
只需要匹配嵌套文檔中的某個特定索引值即可。
對於到java用戶端則為:
已MongoTemplate為例
Criteria criatira = new Criteria(); criatira.andOperator(Criteria.where("login_user.phone").is(110)); Query query = new Query(criatira); Customer customer = mongoTemplate.findOne(query,Customer.class);
LoginUser loginUser = new LoginUser(xxxx); Criteria criatira = new Criteria(); criatira.andOperator(Criteria.where("login_user").is(loginUser)); Query query = new Query(criatira); Customer customer = mongoTemplate.findOne(query,Customer.class);