Jongo框架的目的是使在MongoDB中可以直接使用的查询Shell可以直接在Java中使用。在官网首页有一个非常简洁的例子:
SHELL:这种查询方式是MongoDB数据库支持的查询方式。
JAVA DRIVER:是MongoDB Java驱动API中提供的查询方式
JONGO:就是jongo框架提供的查询方式。
由此可以看出,JONGO框架的意图很明显。
关于MongoDB的安装在此不作赘述,大家可以去它的官网上查看,介绍的非常详细了, http://docs.mongodb.org/manual/installation/。
在Jongo的官网上,介绍说jongo框架的使用依赖于 Jackson 2.2.3, Bson4Jackson 2.2.3 and Mongo Java Driver 2.11+,而jongo目前最新的版本为1.0。通过我的尝试,我发现在实际应用中需要用到以下jar包:
bson4jackson-2.3.1.jar
jackson-annotations-2.4.1.jar
jackson-core-2.4.1.1.jar
jackson-databind-2.4.1.2.jar
jongo-1.0.jar
mongo-java-driver-2.12.2.jar
这些jar包都可以在Maven仓库中找到, http://mvnrepository.com/
Jongo官网: http://jongo.org/
Jongo API: https://jongo.ci.cloudbees.com/job/jongo-ci/site/apidocs/index.html
Jongo GitHub: https://github.com/bguerout/jongo
PersonInfo类
package com.jongo.enties; public class PersonInfo { private int id; private String person_name; private String sex; private String relationship; public PersonInfo() { } //getter and setter @Override public String toString() { return "PersonInfo [id=" + id + ", person_name=" + person_name + ", sex=" + sex + ", relationship=" + relationship + "]"; } }
package com.jongo.demo; import java.util.Iterator; import org.jongo.Jongo;import org.jongo.MongoCollection; import com.jongo.enties.PersonInfo;import com.mongodb.DB;import com.mongodb.MongoClient; public class FirstDemo { public static void main(String[] args) { MongoClient mongo = null; try { mongo = new MongoClient("localhost",27017); DB db = mongo.getDB("jongo"); Jongo jongo = new Jongo(db); MongoCollection person_info = jongo.getCollection("person_info"); @SuppressWarnings("unchecked") Iterator<PersonInfo> all = (Iterator<PersonInfo>) person_info.find().as(PersonInfo.class); while(all.hasNext()) { PersonInfo personInfo = all.next(); System.out.println("all:"+personInfo); } PersonInfo one = (PersonInfo) person_info.findOne("{id:1}").as(PersonInfo.class); System.out.println("one:"+one); } catch(Exception e) { e.printStackTrace(); } finally { if(mongo != null) { mongo.close(); } } } }
运行结果:
all:PersonInfo [id=1, person_name=xiaoming, sex=Man, relationship=Friend] all:PersonInfo [id=2, person_name=xiaohong, sex=Male, relationship=Friend] one:PersonInfo [id=1, person_name=xiaoming, sex=Man, relationship=Friend]
PersonInfo personInfo = new PersonInfo(4,"Marry","Male","ClassMate"); mcoll.save(personInfo);
在Jongo中,Update语法和Mongo Shell有一点点不同,修改的查询语句需要通过使用with()来实现,with()内可以包含一个字符串,或者是一个对象。
(1)person_info.update(new ObjectId("53cb7d99b963ac657273328c")).with("{$inc: {id: 2}}"); 原始记录:{ "_id" : ObjectId("53cb7d99b963ac657273328c"), "id" : 6, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate" } 更新后:{ "_id" : ObjectId("53cb7d99b963ac657273328c"), "id" : 8, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate" } (2)person_info.update("{person_name : 'Dark'}").with("{$set:{person_name:'Dark Update'}}"); 原始记录:{ "_id" : ObjectId("53cb7d91b963ac657273328a"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate" } 更新后:{ "_id" : ObjectId("53cb7d91b963ac657273328a"), "id" : 5, "person_name" : "Dark Update", "sex" : "Male", "relationship" : "ClassMate" } 这种Update方式只会改变第一个被找到的记录。而下面这种方式将会更新所有person_name为Dark的记录: person_info.update("{person_name : 'Dark'}").multi().with("{$set:{person_name:'Dark Update'}}"); (3)person_info.update("{person_name : 'Dark'}").with(new PersonInfo(10, "Dark Update Object", "Man", "ClassMate")); 原始记录:{ "_id" : ObjectId("53cb82ebb963ac657273329d"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate" } 更新后:{ "_id" : ObjectId("53cb82ebb963ac657273329d"), "id" : 10, "person_name" : "Dark Update Object", "sex" : "Man", "relationship" : "ClassMate" } (4)person_info.update("{person_name : 'Dark'}").with("{$set:{address:#}}",new Address("0755","shenzhen")); 原始记录:{ "_id" : ObjectId("53cb8310b963ac657273329e"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate" } 更新后:{ "_id" : ObjectId("53cb8310b963ac657273329e"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate", "address" : { "regionI d" : "0755", "provinceName" : "shenzhen" } }
(1)person_info.insert("{person_name:'Insert Demo'}");
结果:{ "_id" : ObjectId("53cb85cf2fd87f4058d1ff93"), "person_name" : "Insert Demo" }
(2)插入一条记录
PersonInfo personInfo = new PersonInfo(6,"Marry Insert","Male","ClassMate");
person_info.insert(personInfo);
结果:{ "_id" : ObjectId("53cb85e0b963ac65727332a3"), "id" : 6, "person_name" : "Marry Insert", "sex" : "Male", "relationship" : "ClassMate" }
(3)插入多条记录:
PersonInfo personInfo2 = new PersonInfo(7,"Marry Insert2","Male","ClassMate");
person_info.insert(personInfo,personInfo2); //方式一
person_info.insert(new Object[]{personInfo,personInfo2});//方式二
person_info.remove(); //删除所有
person_info.remove(new ObjectId("53cb87c02fd8f9ffd258ceb3"));
person_info.remove("{person_name:'Marry Insert'}");
在Jongo中,Query和Mongo Shell中的Query几乎是一致的。
我们先来看看在Mongo Shell中如何查询:
原始记录:{ "_id" : ObjectId("53cb8e8a2602b31118434306"), "id" : 2, "person_name" : "xiaohong", "sex" : "Male", "relationship" : "Friend" }
//对于数字类型
> db.person_info.find({id:2});
或者> db.person_info.find({"id":2});
{ "_id" : ObjectId("53cb8e8a2602b31118434306"), "id" : 2, "person_name" : "xiaohong", "sex" : "Male", "relationship" : "Friend" }
//对于字符串类型
> db.person_info.find({person_name:'xiaohong'});
或者> db.person_info.find({"person_name":"xiaohong"});
{ "_id" : ObjectId("53cb8e8a2602b31118434306"), "id" : 2, "person_name" : "xiaohong", "sex" : "Male", "relationship" : "Friend" }
那么,在Jongo中怎么查询呢?其实,在上面的第一个简单例子中我们已经见识过了,
Iterator<PersonInfo> all = (Iterator<PersonInfo>) person_info.find().as(PersonInfo.class);
PersonInfo one = (PersonInfo) person_info.findOne("{id:1}").as(PersonInfo.class);
我们再来看看这种文档结构:
{ "_id" : ObjectId("53cb9015b963ac65727332a4"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate", "address" : { "regionId" : "0755", "provinceName" : "shenzhen" } }
假如我要查询出address中regionId为0755的记录,该怎么做?
在Mongo Shell中,我们是这样查询的:
db.person_info.find({"address.regionId":"0755"});
或者db.person_info.find({'address.regionId':'0755'});
在Jongo中的做法也是如出一辙,
PersonInfo personInfo = (PersonInfo) person_info.findOne("{address.regionId:'0755'}").as(PersonInfo.class);
我们一般通过{field:1}或{field:0}来控制查询字段的显示与否。
在Mongo Shell中,做法如下:
> db.person_info.find({},{person_name:1,_id:0}); //查询出person_name,不查询出_id。
{ "person_name" : "xiaohong" }
{ "person_name" : "Dark" }
而在Jongo中我们需要使用projection来到达这种效果。
PersonInfo personInfo = (PersonInfo) person_info.findOne().projection("{person_name:1,id:1}").as(PersonInfo.class);
在Jongo中Sort、Skip、Limit、Hint、Count基本和Mongo Shell一致。
假设数据集合中有这样两条记录:
> db.person_info.find() { "_id" : ObjectId("53cb8e8a2602b31118434306"), "id" : 2, "person_name" : "xiaohong", "sex" : "Male", "relationship" : "Friend" } { "_id" : ObjectId("53cb9015b963ac65727332a4"), "id" : 5, "person_name" : "Dark", "sex" : "Male", "relationship" : "ClassMate", "address" : { "regionId" : "0755", "provinceName" : "shenzhen" } } //sort {field:1} 升序,{field:-1} 降序 Iterator<PersonInfo> sort = (Iterator<PersonInfo>) person_info.find().sort("{id:1}").as(PersonInfo.class); //查询时跳过多少条记录 Iterator<PersonInfo> skip = (Iterator<PersonInfo>) person_info.find().skip(1).as(PersonInfo.class); //查询指定数量的记录 Iterator<PersonInfo> limit = (Iterator<PersonInfo>) person_info.find().limit(2).as(PersonInfo.class); //在查询过程中强制使用hint指定的索引方式,注意必须事先建立person_name字段的倒序索引。 Iterator<PersonInfo> hint = (Iterator<PersonInfo>) person_info.find().hint("{person_name:-1}").as(PersonInfo.class); //查询满足条件的记录数 long len = person_info.count("{id:5}");
在映射部分,_id的定义可有注解@ObjectId来控制,如果你想完全地避免使用原先驱动包的ObjectId,可以使用Jongo提供的Oid类。其用法如下:
import static org.jongo.Oid.withOid; PersonInfo personInfo= new PersonInfo(); // @ObjectId String _id PersonInfo类中需要定义一个名为_id的字段,且加上@ObjectId注解 person_info.save(personInfo); person_info.find(withOid(personInfo._id)).as(PersonInfo .class); // instead of new ObjectId(personInfo._id)
几乎所有查询Jongo可以模板化:添加锚#。绑定参数可以BSON原语或任何复杂类型。
PersonInfo personInfo = person_info.findOne("{id:#,person_name:#}",2,"xiaohong") .as(PersonInfo.class); //相当于findOne("{id:2,person_name:'xiaohong'}") PersonInfo personInfo2 = person_info.findOne("{address:#}",new Address("0755","shenzhen")) .as(PersonInfo.class); //相当于 db.person_info.findOne({'address.regionId':'0755','address.privinceName':'shenzhen'}); Iterator<PersonInfo> ite = (Iterator<PersonInfo>) person_info.find("{id:{$in:#}}",ids) .as(PersonInfo.class); //相当于db.person_info.find({id:{$in:[2,5]}});
以下几种正则查询都是等价的:
PersonInfo personInfo1 = person_info.findOne("{person_name:{$regex:#}}","Dar.*").as(PersonInfo.class); PersonInfo personInfo2 = person_info.findOne("{person_name:{$regex:'Dar.*'}}").as(PersonInfo.class); PersonInfo personInfo3 = person_info.findOne("{person_name:#}",Pattern.compile("Dar.*")).as(PersonInfo.class); Pattern p = Pattern.compile("Dar.*"); PersonInfo personInfo4 = person_info.findOne("{person_name:{$regex:'"+p+"'}}").as(PersonInfo.class);
1、Distinct
List<String> personNames = person_info.distinct("person_name").as(String.class); List<Address> addresses = person_info.distinct("address").query("{id:5}").as(Address.class); int size = person_info.distinct("address").query("{id:5}").as(Address.class).size();
2、聚合框架
这个特性只能在Mongo2.2以上版本中使用,所有诸如$project, $match, $limit, $skip, $unwind, $group, $sort的聚合操作都支持。在官网有一个例子:
collection.aggregate("{$project:{sender:1}}") .and("{$match:{tags:'read'}}") .and("{$limit:10}") .as(Email.class);
3、对象映射
查询结果自动映射到对象,它依赖于Jackson,涉及文档结构,处理列表以及忽略缺失的属性。仅仅需要一个无参构造器(甚至私有构造器都行,前提是对象是不可变的,注解@JsonCreator可以用来替代)
_id在每个MongoDB文档中是一个唯一的标识符,如果没有被设定,它将自动生成,用Jongo来定义它时,一个属性需要被命名为_id或者带有@Id注解(别名 @JsonProperty("_id")),可以使用专门的ObjectId类或者一个简单的由@ObjectId注解的简单字符串来定义。
需要注意的是,当你保存一个自定义的文档_id时(任何Java类型,除了数组意外,只要它是唯一值)总是需要在持久化之前手动的去进行设置。
以下几种情形式需要手动设置_id的:
而下面这几种是自动生成的: