您的位置:首页 > 数据库 > Mongodb

MongoDB,java操作

2011-08-24 10:15 411 查看
使用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 “update if present; insert if missing”.

myColl.update( { _id: X }, { _id: X, name: "Joe", age: 20 }, true );

Modifier Operations

Modifier operations are highly-efficient and useful when updating existing values; for instance, they’re great for incrementing a number.

So, while a conventional implementation does work:

var j=myColl.findOne( { name: "Joe" } );

j.n++;

myColl.save(j);

a modifier update has the advantages of avoiding the latency involved in querying and returning the object. The modifier update also features operation atomicity and very little network data transfer.

To perform an atomic update, simply specify any of the special update operators (which always start with a ‘$’ character) with a relevant update document:

db.people.update( { name:"Joe" }, { $inc: { n : 1 } } );

The preceding example says, “Find the first document where ‘name’ is ‘Joe’ and then increment ‘n’ by one.”

While not shown in the examples, most modifier operators will accept multiple field/value pairs when one wishes to modify multiple fields. For example, the following operation would set x to 1 and y to 2:

{ $set : { x : 1 , y : 2 } }

Also, multiple operators are valid too:

{ $set : { x : 1 }, $inc : { y : 1 } }

$inc

{ $inc : { field : value } }

increments field by the number value if field is present in the object, otherwise sets field to the number value.

$set

{ $set : { field : value } }

sets field to value. All datatypes are supported with $set.

$unset

{ $unset : { field : 1} }

Deletes a given field. v1.3+

$push

{ $push : { field : value } }

appends value to field, if field is an existing array, otherwise sets field to the array [value] if field is not present. Iffield is present but is not an array, an error condition is raised.

$pushAll

{ $pushAll : { field : value_array } }

appends each value in value_array to field, if field is an existing array, otherwise sets field to the array value_arrayif field is not present. If field is present but is not an array, an error condition is raised.

$addToSet

{ $addToSet : { field : value } }

Adds value to the array only if its not in the array already, if field is an existing array, otherwise sets field to the arrayvalue if field is not present. If field is present but is not an array, an error condition is raised.

To add many valuest.update

{ $addToSet : { a : { $each : [ 3 , 5 , 6 ] } } }

$pop

{ $pop : { field : 1 } }

removes the last element in an array (ADDED in 1.1)

{ $pop : { field : -1 } }

removes the first element in an array (ADDED in 1.1) |

$pull

{ $pull : { field : _value } }

removes all occurrences of value from field, if field is an array. If field is present but is not an array, an error condition is raised.

In addition to matching an exact value you can also use expressions ($pull is special in this way):

{ $pull : { field : {field2: value} } } removes array elements with field2 matching value

{ $pull : { field : {$gt: 3} } } removes array elements greater than 3

{ $pull : { field : {<match-criteria>} } } removes array elements meeting match criteria

Because of this feature, to use the embedded doc as a match criteria, you cannot do exact matches on array elements.

$pullAll

{ $pullAll : { field : value_array } }

removes all occurrences of each value in value_array from field, if field is an array. If field is present but is not an array, an error condition is raised.

$rename

Version 1.7.2+ only.

{ $rename : { old_field_name : new_field_name } }

Renames the field with name ‘old_field_name’ to ‘new_field_name’. Does not expand arrays to find a match for ‘old_field_name’.

The $ positional operator

Version 1.3.4+ only.

The $ operator (by itself) means “position of the matched array item in the query”. Use this to find an array member and then manipulate it. For example:

> t.find()

{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",

"comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }

> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true )

> t.find()

{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",

"comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }

Currently the $ operator only applies to the first matched item in the query. For example:

> t.find();

{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }

> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);

> t.find();

{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }

The positional operator cannot be combined with an upsert since it requires a matching array element. If your update results in an insert then the “$” will literally be used as the field name.

Using “$unset” with an expression like this “array.$” will result in the array item becoming null, not being removed. You can issue an update with “{$pull:{x:null}}” to remove all nulls.

> t.insert({x: [1,2,3,4,3,2,3,4]})

> t.find()

{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }

> t.update({x:3}, {$unset:{"x.$":1}})

> t.find()

{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }

$pull can now do much of this so this example is now mostly historical (depending on your version).

Upserts with Modifiers

You may use upsert with a modifier operation. In such a case, the modifiers will be applied to the update criteria member and the resulting object will be inserted. The following upsert example may insert the object {name:"Joe",x:1,y:1}.

db.people.update( { name:"Joe" }, { $inc: { x:1, y:1 } }, true );

There are some restrictions. A modifier may not reference the _id field, and two modifiers within an update may not reference the same field, for example the following is not allowed:

db.people.update( { name:"Joe" }, { $inc: { x: 1 }, $set: { x: 5 } } );

Pushing a Unique Value

To add a value to an array only if not already present:

Starting in 1.3.3, you can do

update( {_id:'joe'},{"$addToSet": { tags : "baseball" } } );

For older versions, add $ne : <value> to your query expression:

update( {_id:'joe', tags: {"$ne": "baseball"}},

{"$push": { tags : "baseball" } } );

Checking the Outcome of an Update Request

As described above, a non-upsert update may or may not modify an existing object. An upsert will either modify an existing object or insert a new object. The client may determine if its most recent message on a connection updated an existing object by subsequently
issuing a getlasterror command ( db.runCommand( "getlasterror" ) ). If the result of thegetlasterror command contains an updatedExisting field, the last message on the connection was an update request. If the updatedExisting field’s value is true, that update
request caused an existing object to be updated; if updatedExistingis false, no existing object was updated. An upserted field will contain the new _id value if an insert is performed (new as of 1.5.4).

Notes

Object Padding

When you update an object in MongoDB, the update occurs in-place if the object has not grown in size. This is good for insert performance if the collection has many indexes.

Mongo adaptively learns if objects in a collection tend to grow, and if they do, it adds some padding to prevent excessive movements. This statistic is tracked separately for each collection.

Blocking

Staring in 1.5.2, multi updates yield occasionally so you can safely update large amounts of data. If you want a multi update to be truly isolated (so no other writes happen while processing the affected documents), you can use the $atomic flag in the query
like this:

db.students.update({score: {$gt: 60}, $atomic: true}, {$set: {pass: true}})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: