mongodb-java_java操作mongodb(一)之新增、查询

[上篇博客介绍了java操作mongoDB进行对文件的处理。现在来介绍一下对文档的处理。和对文件的处理一样,也是通过java驱动中提供的几个类相互作用完成的。这几个类分别是:

1、基于官方mongo-java-driver.2.9.1,在项目中pom依赖

org.mongodb

mongo-java-driver

2.9.1

2、mongodb启动

在win7-32中

mongod.exe --help

mongod.exe --dbpath D:\mongodb\data\db --auth -logpath D:\mongodb\log.log

这里指定了数据库位置,--auth设置权限,这样访问mongo的所有数据库就需要授权才能访问。下面对数据库(sample)设置用户权限,在mongodb的shell中:

1、mongo.exe

2、use sample;

3、show collections;

system.indexes

system.users

user

4、db.addUser('sa','sa')

5、show collections;

Fri Oct 26 11:33:53 uncaught exception: error: {

"$err" : "unauthorized db:sample lock type:-1 client:127.0.0.1",

"code" : 10057

}

6、db.auth('sa','sa')

7、show collections;

system.indexes

system.users

user

3、几个基本概念

这里借鉴熟知的jdbc链接的步骤,我们可以用如下的步骤来:

//1、建立连接

Mongo mongo = new Mongo("127.0.0.1", 27017);

//2、获取文档(数据库),这里为sample

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

//3、验证用户

if (db.authenticate("sa", "sa".toCharArray())) {

//4、获取连接,这里是对集合user的操作

DBCollection collection = db.getCollection("user");

//对集合(表)进行各种操作(增删改查)

DBObject obj = collection.findOne()

}

以上的过程就类似我们建立一个jdbc的链接,其中与DriverManager、Connection、Statement 、ResultSet等很类似。

对在第二部中的安全设置是在shell中完成的,这里在DB中同样提供了对数据库操作的API:

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

db.addUser("sa", "sa".toCharArray());

4、基本操作

对集合的操作主要是在DBCollection中,提供了一系列增删改查抽象或方法。下面来依次来看看这些方法的使用。

4、1插入

这里主要采用insert的几种多态接口,提供了对单个或批量的支持,同时也支持插入策略限定(WriteConcern)

f31b15a99c3202c3f9aaf2c1410a2f07.png[import java.net.UnknownHostException;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.DBCursor;import com.mongodb.Mongo;import com.mong 其中 DBObject是一个key-value的map对应保存数据库的数据 WriteConcern是控制写入策略,主要有三个方面的参数

public WriteConcern( int w , int wtimeout , boolean fsync ){

this(w, wtimeout, fsync, false);

}

w

-1 = don't even report network errors

0 = default, don't call getLastError by default

1 = basic, call getLastError, but don't wait for slaves

2+= wait for slaves

wtimeout how long to wait for slaves before failing

0 = indefinite

>0 = ms to wait

fsync force fsync to disk  我们以插入以下内容为例:

{"name" : "mongo" , "type" : "db" , "info" : { "comp" : "10gen" , "driver" : "java"}} 采用BasicDBObject封装插入数据,继承自DBObject,支持多种数据格式

//用BasicDBObject作为插入的封装数据

BasicDBObject user = new BasicDBObject();

user.put("name", "mongo");

user.put("type", "DB");

//这里是子对象

BasicDBObject info = new BasicDBObject();

info.put("comp", "10gen");

info.put("driver", "java");

user.put("info", info);

collection.insert(user);

采用BasicDBObjectBuilder

BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("name", "mongo").add("type", "DB");

BasicDBObjectBuilder info = BasicDBObjectBuilder.start().add("comp", "10gen").add("driver", "java");

builder.add("info", info.get());

collection.insert(builder.get());

同样也支持Map,用法与上面的一致。 对批量的支持也一样,传入List或DBObeject数组即可,如:

WriteResult result = collection.insert(list, WriteConcern.SAFE);

这里是否返回插入错误信息依赖插入的策略WriteConcern.SAFE

4、2查找

更新一系列方法与插入类似,接受DBObject根据查询条件返回DBObject(单个)或DBCursor(多个)

386d4cb3e0a75f1f7705da5556e5bf3e.png

下面是一些常用的api:

//查找一个,当然返回任意一个没多大实际意义

DBObject obj = collection.findOne();

//查找一个:name=mongo

DBObject obj = collection.findOne(new BasicDBObject("name", "mongo"));

//查找多个:满足name=mongo的所有结果集

DBCursor cursor = collection.find(new BasicDBObject("name", "mongo"));

//查找多个:满足age在(30,40]的所有结果集:"$gt": 大于 "$gte":大于等于 "$lt": 小于 "$lte":小于等于

DBCursor cursor = collection.find(new BasicDBObject("age", new BasicDBObject("$gt", 30).append("$lte", 40)));

//查询分页

DBCursor cursor = collection.find(new BasicDBObject("age", new BasicDBObject("$gt", 30).append("$lte", 60)))

.skip(0).limit(5);

//模糊匹配:username like robin(正则匹配)

DBCursor cursor = collection.find(new BasicDBObject("username", Pattern.compile("robin")));

//根据子文档查询:

DBCursor cursor = collection.find(new BasicDBObject("info.comp", "10gen"));

//返回指定的列

DBCursor cursor = collection.find(new BasicDBObject("name", "mongo"),

new BasicDBObject("name", 1).append("type", 1));

以上DBCursor是数据库结果集的迭代,我们可以通过

DBCursor cursor = collection.find( query );

if( cursor.hasNext() )

DBObject obj = cursor.next();

来获取数据。同时DBCursor还提供了对查询的限定,如前面说到的skip()、limit()等,还介绍几个常用的方法:

1、public DBCursor sort( DBObject orderBy )//与order by类似

2、public DBCursor hint( DBObject indexKeys )//强制使用索引

3、public DBObject explain() //explain不解释

4、public DBCursor batchSize( int n )//限制一次返回数据

5、public int count()//返回匹配的数量,不受limit/skip影响

6、public int size() //返回当前查询返回数量,受limit/skip影响

[直接上代码(依赖代码请查看之前的博客):public void query() {// $or (查询id等于1或者id等于2的数据)BasicDBObject queryObject = new BasicDBObject().append(

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值