MongoDB,java操作

來源:互聯網
上載者:User

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

Regex
查詢所有名字匹配 /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}})

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.