Spring Boot MongoDB 查询操作 (BasicQuery ,BSON)

MongoDB 查询有四种方式:Query,TextQuery,BasicQuery 和 Bson ,网上太多关于 Query 的查询方式,本文只记录 BasicQuery和Bson 的方式,BasicQuery 相对于 Query 更加的灵活,BasicQuery 就是 Query 的扩展,BasicQuery 可以返回指定列数据。最灵活的是Bson方式。

大写的采坑经验

1.MongoDB 虽然存储很灵活,但是,不要存储Map类型的,不要存储Map类型的,不要存储Map类型的。尽量存储强类型的,尽量存储强类型的,尽量存储强类型的。如果有Map类型的,对于查询指定列的,只能用Bson ,如果是强类型的,就可以直接用Query,TextQuery。

2.复杂类型查询 可以考虑 Bson 方式,Bson 请参考文章最后。

 

 安装Maven包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

 

测试数据代码

 for (Long i = 0L; i < 10L; i++) {
     MongoDBTestVo vo=new MongoDBTestVo();
     vo.setUserId(i);
     vo.setEmail("1@1.com");
     vo.setName("test"+i.toString());
     vo.setPhone(i.toString());
     vo.setCreateDate(new Date());
     mongoTemplate.insert(vo,"mongodbtest");
}
public class MongoDBTestVo implements Serializable {
    private Long userId;
    private String email;
    private String name;
    private String phone;
    private Date createDate;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}
MongoDBTestVo Code

 

单条件查询

DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2)); // userId>=2的条件
//
obj.put("userId", 2); userId=2 的条件
Query query = new BasicQuery(obj.toString()); 
List
<MongoDBTestVo> result = mongoTemplate.find(query, MongoDBTestVo.class, "mongodbtest");

 

多条件查询

BasicDBList basicDBList = new BasicDBList();
basicDBList.add(new BasicDBObject("userId", 2L));
basicDBList.add(new BasicDBObject("name","test2"));

DBObject obj = new BasicDBObject();
obj.put("$and", basicDBList);

Query query = new BasicQuery(obj.toString());

List<MongoDBTestVo> result = mongoTemplate.find(query, MongoDBTestVo.class, "mongodbtest");

 

查看指定列的数据

DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2));

BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("userId", 1);
fieldsObject.put("name", 1);

Query query = new BasicQuery(obj.toString(), fieldsObject.toString());

List<Map> result = mongoTemplate.find(query, Map.class, "mongodbtest");

BasicQuery查询语句可以指定返回字段,构造函数BasicQuery(DBObject queryObject, DBObject fieldsObject),fieldsObject 这个字段可以指定返回字段

fieldsObject.put(key,value)

            key:字段

           value:

             说明:

                  1或者true表示返回字段

                 0或者false表示不返回该字段

               _id:默认就是1,没指定返回该字段时,默认会返回,除非设置为0是,就不会返回该字段。

指定返回字段,有时文档字段多并数据大时,我们指定返回我们需要的字段,这样既节省传输数据量,减少了内存消耗,提高了性能,在数据大时,性能很明显的。

 

Bson查询方式

Bson bson = Filters.and(Arrays.asList(
                    Filters.gte("createdTime", Calendar.getInstance().getTime()),
                    Filters.gte("apis.count", 1)));
MongoCursor<Document> cursor = null;
try {
    FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson);
    cursor = findIterable.iterator();
    List<MongoDBTestVo> list = new ArrayList<>();
    while (cursor.hasNext()) {
          Document object = cursor.next();
          MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
          list.add(entity);
     }
     return list;
} finally {
   if (cursor != null) {
       cursor.close();
   }
}

 Bson返回指定列

Bson bson = Filters.and(Arrays.asList(
                    Filters.gte("createdTime", Calendar.getInstance().getTime()),
                    Filters.gte("apis.count", 1)));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("apis.count", 1);
fieldsObject.put("_id", 0);
MongoCursor<Document> cursor = null;
try {
    FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson).projection(Document.parse(fieldsObject.toString()));
    cursor = findIterable.iterator();
    List<MongoDBTestVo> list = new ArrayList<>();
    while (cursor.hasNext()) {
          Document object = cursor.next();
          MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
          list.add(entity);
     }
     return list;
} finally {
   if (cursor != null) {
       cursor.close();
   }
}

 Bson 排序

Bson bson = Filters.and(Arrays.asList(
Filters.gte("createdTime", Calendar.getInstance().getTime()),
Filters.gte("apis.count", 1)));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("apis.count", 1);
fieldsObject.put("_id", 0);
BasicDBObject sort = new BasicDBObject();
sort.put("createdTime", 1);
MongoCursor<Document> cursor = null;
try {
    FindIterable<Document> findIterable = mongoTemplate.getCollection("mongodbtest").find(bson).projection(Document.parse(fieldsObject.toString())).sort(sort);
    cursor = findIterable.iterator();
    List<MongoDBTestVo> list = new ArrayList<>();
    while (cursor.hasNext()) {
          Document object = cursor.next();
          MongoDBTestVo entity = JSON.parseObject(object.toJson(), MongoDBTestVo.class);
          list.add(entity);
     }
     return list;
} finally {
   if (cursor != null) {
       cursor.close();
   }
}

 

posted @ 2018-11-01 10:44  bookc  阅读(6295)  评论(2编辑  收藏  举报