MongoDB嵌套查询

转载自: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);

猜你喜欢

转载自blog.csdn.net/wendrewshay/article/details/78498656