mongodb java 框架_MongoDB框架Jongo的使用介绍

1、Jongo可以用来做什么?

Jongo框架的目的是使在MongoDB中可以直接使用的查询Shell可以直接在Java中使用。在官网首页有一个非常简洁的例子:

3857386.html

1ede9f21963d9e6ea7d81f165a8327f7.png

SHELL:这种查询方式是MongoDB数据库支持的查询方式。

JAVA DRIVER:是MongoDB Java驱动API中提供的查询方式

JONGO:就是jongo框架提供的查询方式。

由此可以看出,JONGO框架的意图很明显。

2、Jongo的下载

在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

3、Jongo的使用

PersonInfo类:

1 packagecom.jongo.enties;2

3 public classPersonInfo {4

5 private intid;6 privateString person_name;7 privateString sex;8 privateString relationship;9

10 publicPersonInfo() {11

12 }13 //getter and setter

14 @Override15 publicString toString() {16 return "PersonInfo [id=" + id + ", person_name=" +person_name17 + ", sex=" + sex + ", relationship=" + relationship + "]";18 }19 }

1)第一个简单的例子

packagecom.jongo.demo;importjava.util.Iterator;importorg.jongo.Jongo;importorg.jongo.MongoCollection;importcom.jongo.enties.PersonInfo;importcom.mongodb.DB;importcom.mongodb.MongoClient;public classFirstDemo {public static voidmain(String[] args) {

MongoClient mongo= null;try{

mongo= new MongoClient("localhost",27017);

DB db= mongo.getDB("jongo");

Jongo jongo= newJongo(db);

MongoCollection person_info= jongo.getCollection("person_info");

@SuppressWarnings("unchecked")

Iterator all = (Iterator) 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]

2)Jongo的Save

PersonInfo personInfo = new PersonInfo(4,"Marry","Male","ClassMate");

mcoll.save(personInfo);

3)Jongo的Update

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

4)Jongo的Insert

(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});//方式二

5)Jongo的Remove

person_info.remove(); //删除所有

person_info.remove(new ObjectId("53cb87c02fd8f9ffd258ceb3"));

person_info.remove("{person_name:'Marry Insert'}");

6)Jongo的Query

在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 all = (Iterator) 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" : { "regionI

d" : "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);

7)Jongo如何查询出指定字段(不查询某字段)?

我们一般通过{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);

8)Jongo的Sort、Skip、Limit、Hint、Count

在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" : { "regionI

d" : "0755", "provinceName" : "shenzhen" } }

Iterator sort = (Iterator) person_info.find().sort("{id:1}").as(PersonInfo.class);//sort {field:1} 升序,{field:-1} 降序

Iterator skip = (Iterator) person_info.find().skip(1).as(PersonInfo.class);//查询时跳过多少条记录

Iterator limit = (Iterator) person_info.find().limit(2).as(PersonInfo.class);//查询指定数量的记录

Iterator hint = (Iterator) person_info.find().hint("{person_name:-1}").as(PersonInfo.class);//在查询过程中强制使用hint指定的索引方式,注意必须事先建立person_name字段的倒序索引。

long len = person_info.count("{id:5}");//查询满足条件的记录数

9)Jongo的Oid

在映射部分,_id的定义可有注解@ObjectId来控制,如果你想完全地避免使用原先驱动包的ObjectId,可以使用Jongo提供的Oid类。其用法如下:

import staticorg.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)

10)Jongo的查询模板

几乎所有查询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 ite = (Iterator) person_info.find("{id:{$in:#}}",ids).as(PersonInfo.class); //相当于db.person_info.find({id:{$in:[2,5]}});

11)Jongo的正则查询

以下几种正则查询都是等价的:

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

12)Jongo的聚合操作

(1)Distinct

List personNames = person_info.distinct("person_name").as(String.class);

List

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

4、对象映射

查询结果自动映射到对象,它依赖于Jackson,涉及文档结构,处理列表以及忽略缺失的属性。仅仅需要一个无参构造器(甚至私有构造器都行,前提是对象是不可变的,注解@JsonCreator可以用来替代)

_id在每个MongoDB文档中是一个唯一的标识符,如果没有被设定,它将自动生成,用Jongo来定义它时,一个属性需要被命名为_id或者带有@Id注解(别名 @JsonProperty("_id")),可以使用专门的ObjectId类或者一个简单的由@ObjectId注解的简单字符串来定义。

需要注意的是,当你保存一个自定义的文档_id时(任何Java类型,除了数组意外,只要它是唯一值)总是需要在持久化之前手动的去进行设置。

以下几种情形式需要手动设置_id的:

97877e8b435f09d841182602c6718812.png

3857386.html

而下面这几种是自动生成的:

e2739b08e4bd1848067d040e48f91fc5.png

3857386.html

mongodb-orm简介Mongodb ORM是基于java的ORM框架,简化了SDK的使用,使代码变得更清晰、简单。 与Ibatis类似,将查询、执行语句封装在xml中,与代码隔离。简称MQL。 项目中使用加入mongodb orm的支持包1. 添加jar包或maven支持<dependency>     <groupId>com.mongodborm</groupId>     <artifactId>mongodb-orm</artifactId>     <version>0.0.1-RELEASE</version> </dependency>2. 初始化mongodb templet        spring中初始化<bean id="mongoTemplet" class="com.mongodb.client.MongoClientTemplet">     <property name="factory">         <bean class="com.mongodb.client.MongoORMFactoryBean">             <property name="dataSource">                 <bean class="com.mongodb.client.MongoDataSource">                     <property name="nodeList" value="127.0.0.1:27017" />                     <property name="dbName" value="your db name" />                     <property name="userName" value="user name" />                     <property name="passWord" value="password" /> <!-- 可使用默认值 --> <property name="connectionsPerHost" value="" />                     <property name="threadsAllowedToBlock" value="" />                     <property name="connectionTimeOut" value="" />                     <property name="maxRetryTime" value="" />                     <property name="socketTimeOut" value="" />                 </bean>             </property>             <property name="configLocations">                 <list>                     <value>classpath:mql/mongo-mql.xml</value>                 </list>             </property>         </bean>     </property> </bean>        代码初始化    try {       Resource resource =  new ClassPathResource("mongo-mql.xml");           MongoORMFactoryBean factory = new MongoORMFactoryBean();       factory.setConfigLocations(new Resource[]{resource});       factory.init();          MongoClientTemplet templet = new MongoClientTemplet();       templet.setFactory(factory);       templet.init();     } catch(Exception e) {       e.printStackTrace();     }编写MQLMapping<mapping id="model" class="test.mongodborm.Model">         <property column="_id" name="id" />         <property column="name" name="name" />         <property column="time" name="time" value="0" />         <property column="status" name="status" /> </mapping> <mapping id="extendModel" class="test.mongodborm.Model" extends="model">     <property column="newProperty" name="newProperty" /> </mapping>  select<select id="queryModelList" collection="test_sample">     <query class="java.lang.String">         <property column="name" name="${value}" />     </query>     <field mapping="model" />     <order>         <property column="time" value="desc" />     </order> </select> update/findAndModify<update id="updateModel" collection="test_sample">     <query class="test.mongodborm.Model$Child">         <property column="name" name="name" ignoreNull="true" />         <property column="time" operate="gte" value="0" type="number" />         <property column="status" operate="in">             <list type="number">0,1</list>         </property>     </query>     <action class="java.util.Map">         <property column="name" name="name" operate="set" />         <property column="status" operate="set" />     </action> </update>有嵌套的查询<select id="queryModelList3" collection="test_sample">     <query class="java.lang.String">         <property column="_id" value="${value}" />         <property column="time" value="0" type="number" />     </query>     <field class="java.util.Map">         <property column="name" name="name" />         <property column="parent" name="parent">             <value class="test.mongodborm.Model$Parent">                 <property column="name" name="name" />                 <property column="child" name="child">                     <value class="test.mongodborm.Model$Child">                         <property column="name" name="name" />                         <property column="time" name="time" value="0" />                     </value>                 </property>                 <property column="data" name="data">                     <value class="java.util.Map">                         <property column="title" name="title" />                         <property column="content" name="content" />                     </value>                 </property>             </value>         </property>         <property column="data" name="data">             <value class="java.util.Map">                 <property column="title" name="title" />                 <property column="content" name="content" />             </value>         </property>     </field>     <order class="java.util.Map">         <property column="time" name="time" value="desc" />     </order> </select>Templet用法Model model = mongoTemplet.findOne("queryModelList", "yuxiangping"); List<Model> list = mongoTemplet.findOne("queryModelList", ""); Model model = new Model(); model.setTime(1L); Map<String, String> action = new HashMap<String, String>(); action.put("name", "yuxiangping-update"); int update = mongoT emplet.update("updateModel", model, action);        更多的使用方法参见 sample.xml 标签:Mongodb
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值