今天在项目中遇到了关于MongoDB嵌套查询,之前一直没有接触过,查询了相关资料后将结果记录下来。
MongoDB中的数据如下:
> db.customer.findOne()
{
"_id" : ObjectId("57636c8e35defe029962107e"),
"_class" : "com.bu2trip.ticket.model.Customer",
"name" : "wang",
"phone" : "18888888888",
"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);