轉載自:http://blog.csdn.net/canot/article/details/51699776 感謝作者
今天在項目中遇到了關於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" : "[email protected]",
"phone" : "110"
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
如果要查詢整個內嵌文檔,查詢語句如下:
db.customer.find({"login_user" : {"_id":ObjectId("5760e593086659036b77c124"), "email" : "[email protected]","phone" : "110"}})
- 1
在查詢條件中必須寫出以login_user爲鍵的所有值。
只針對內嵌文檔的特定鍵值進行查詢如下:
db.customer.findOne({"login_user.phone":"110"})
- 1
只需要匹配嵌套文檔中的某個特定鍵值即可。
對於到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);
- 1
- 2
- 3
- 4
- 5
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);