java操作mongodb
使用mongoDB需要导入以下类,当然不是全部需要,用到的类就导入。
import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ObjectId;
类转换
当把一个类对象存到mongoDB后,从mongoDB取出来时使用setObjectClass()将其转换回原来的类。
public class Tweet implements DBObject {
/* ... */
}
Tweet myTweet = new Tweet();
myTweet.put("user", "bruce");
myTweet.put("message", "fun");
myTweet.put("date", new Date());
collection.insert(myTweet);
//转换
collection.setObjectClass(Tweet);
Tweet myTweet = (Tweet)collection.findOne();
默认ID
当保存的对象没有设置ID时,mongoDB会默认给该条记录设置一个ID("_id")。
当然你也可以设置自己指定的ID,如:(在mongoDB中执行用db.users.save({_id:1,name:'bruce'});)
BasicDBObject bo = new BasicDBObject();
bo.put('_id', 1);
bo.put('name', 'bruce');
collection.insert(bo);
权限
判断是否有mongoDB的访问权限,有就返回true,否则返回false。
boolean auth = db.authenticate(myUserName, myPassword);
查看mongoDB数据库列表
Mongo m = new Mongo();
for (String s : m.getDatabaseNames()) {
System.out.println(s);
}
查看当前库下所有的表名,等于在mongoDB中执行show tables;
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(s);
}
查看一个表的索引
List<DBObject> list = coll.getIndexInfo();
for (DBObject o : list) {
System.out.println(o);
}
删除一个数据库
Mongo m = new Mongo();
m.dropDatabase("myDatabaseName");
建立mongoDB的链接
Mongo m = new Mongo("localhost", 27017);
DB db = m.getDB("myDatabaseName"); //相当于库名
DBCollection coll = db.getCollection("myUsersTable");//相当于表名
#查询数据
查询第一条记录
DBObject firstDoc = coll.findOne();
findOne()返回一个记录,而find()返回的是DBCursor游标对象。
查询全部数据
DBCursor cur = coll.find();
while(cur.hasNext()) {
System.out.println(cur.next());
}
查询记录数量
coll.find().count();
coll.find(new BasicDBObject("age", 26)).count();
设置条件查询
BasicDBObject condition = new BasicDBObject();
condition.put("name", "bruce");
condition.put("age", 26);
coll.find(condition);
查询部分数据块
DBCursor cursor = coll.find().skip(0).limit(10);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
比较查询(age > 50)
BasicDBObject condition = new BasicDBObject();
condition.put("age", new BasicDBObject("$gt", 50));
coll.find(condition);
比较符
"$gt": 大于
"$gte":大于等于
"$lt": 小于
"$lte":小于等于
"$in": 包含
//以下条件查询20<age<=30
condition.put("age", new BasicDBObject("$gt", 20).append("$lte", 30));
#插入数据
批量插入
List datas = new ArrayList();
for (int i=0; i < 100; i++) {
BasicDBObject bo = new BasicDBObject();
bo.put("name", "bruce");
bo.append("age", i);
datas.add(bo);
}
coll.insert(datas);
正则表达式
查询所有名字匹配/joh?n/i 的记录
Pattern pattern = Pattern.compile("joh?n", CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", pattern);
DBCursor cursor = coll.find(query);
mongoDb update的使用方法
关键是在$set,还有很多测试,地址:http://www.mongodb.org/display/DOCS/Updating#Updating-%24inc
?
update(BasicDBobject ,BasicDBobject)
第一个参数是查找条件,需要修改的对象,第二个参数是修改内容,如果不用set就是把原来的对象更新为现在的对象。
如果有$set那就是更新属性,如果属性不存在则添加。其他参数使用方法一样。
?
?
DBCollection coll2 = db.getCollection(Config.SENDER_EMAIL_MESSAGE);
?
coll2.update(
new BasicDBObject("key", sender.get("key")),
new BasicDBObject("$set", new BasicDBObject(
"finallyUseTime", Math.floor(System
.currentTimeMillis()
/ Config.SEND_FREQUENCY))));
?
———————————————————————————————————————————————-
为了方便将完成的内容引用到这里
MongoDB supports atomic, in-place updates as well as more traditional updates for replacing an entire document.
* update()
* save() in the mongo shell
* Modifier Operations
+ $inc
+ $set
+ $unset
+ $push
+ $pushAll
+ $addToSet
+ $pop
+ $pull
+ $pullAll
+ $rename
o The $ positional operator
o Upserts with Modifiers
o Pushing a Unique Value
* Checking the Outcome of an Update Request
* Notes
o Object Padding
o Blocking
* See Also
update()
update() replaces the document matching criteria entirely with objNew. If you only want to modify some fields, you should use the atomic modifiers below.
Here’s the MongoDB shell syntax for update():
db.collection.update( criteria, objNew, upsert, multi )
Arguments:
* criteria – query which selects the record to update;
* objNew – updated object or $ operators (e.g., $inc) which manipulate the object
* upsert – if this should be an “upsert”; that is, if the record does not exist, insert it
* multi – if all documents matching criteria should be updated
If you are coming from SQL, be aware that by default, update() only modifies the first matched object. If you want to modify all matched objects you need to use the multi flag
save() in the mongo shell
The save() command in the mongo shell provides a shorthand syntax to perform a single object update with upsert:
// x is some JSON style object
db.mycollection.save(x); // updates if exists; inserts if new
save() does an upsert if x has an _id field and an insert if it does not. Thus, normally, you will not need to explicitly request upserts, just use save().
Upsert means
补充:软件开发 , Java ,