MongoDB 嵌套查询 使用命令和java代码例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bigtree_3721/article/details/82843381

对于保存在 mongo db 中的类似hashmap等复杂结构查询,可以采用如下的命令和代码来查询。

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"
    }
}

如果要查询整个内嵌文档,完全匹配的查询语句如下:

db.customer.find({"login_user" : {"_id":ObjectId("5760e593086659036b77c124"), "email" : "[email protected]","phone" : "110"}})

在查询条件中必须写出以login_user为键的所有值。只针对内嵌文档的特定键值进行查询如下

db.customer.findOne({"login_user.phone":"110"})

只需要匹配嵌套文档中的某个特定键值即可。

更多如何写嵌套查询的例子见下面的blog:

https://blog.csdn.net/wuhenzhangxing/article/details/73330831

java嵌套查询的官方文档在:

https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#java-sync

对于到java客户端则为: 以spring 带的 MongoTemplate 例子,例子代码如下:

例子1:

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); 

例子2:

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/bigtree_3721/article/details/82843381