`
zhaohaolin
  • 浏览: 1010800 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MongoDB,java操作【转】

    博客分类:
  • JAVA
 
阅读更多

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

分享到:
评论

相关推荐

    MongoDB Java Driver 简单操作

    ### MongoDB Java Driver 简单操作详解 #### 一、简介 MongoDB 是一款非常流行的文档型数据库系统,因其灵活性和高性能而被广泛应用于多种场景之中。为了方便开发者使用 Java 进行开发,MongoDB 提供了官方的 Java ...

    MongoDBjava各版本驱动下载

    MongoDB Java驱动是Java开发者与MongoDB数据库交互的重要工具,它允许Java应用程序通过标准的Java API来执行查询、插入、更新和删除等操作。在Java中使用MongoDB,首先需要安装并配置对应的驱动版本,以确保与正在...

    MongoDB Java操作大全 源代码 实例

    本资料包“MongoDB Java操作大全 源代码 实例”将深入探讨如何使用Java API进行MongoDB的操作。 1. **连接MongoDB** 在Java中,首先需要通过`MongoClient`类建立到MongoDB服务器的连接。例如: ```java ...

    mongodb java简单demo

    本篇将详细介绍如何使用Java连接MongoDB,以及进行基本的数据操作:创建集合、添加文档、修改文档、查询文档和删除文档。 首先,为了连接MongoDB,我们需要引入MongoDB的Java驱动程序依赖。在Maven项目中,可以在...

    mongoDB java driver api

    MongoDB是一个高性能、开源、无模式的文档型数据库,而Java驱动API则为Java开发者提供了一个直观且强大的接口来操作MongoDB。 首先,让我们了解一下MongoDB Java驱动API的基本结构和核心概念: 1. **MongoClient**...

    MongoDB Java API 中文

    ### MongoDB Java API 使用详解 #### 一、Java 驱动简介与一致性 MongoDB 的 Java 驱动是...这些知识点涵盖了大部分常见的 MongoDB 应用场景,可以帮助初学者快速上手并熟练掌握如何使用 Java 驱动进行数据库操作。

    mongodb java Driver

    MongoDB Java驱动程序是Java开发者用来与MongoDB数据库进行交互的一种关键工具。它提供了一组丰富的API,使得在Java应用程序中执行CRUD(创建、读取、更新、删除)操作变得简单而高效。MongoDB是一个分布式文档存储...

    java 操作mongodb 增删改查

    以上就是Java操作MongoDB的基本步骤。这个“mongodb_helloworld”项目应该包含示例代码,帮助初学者快速上手。记得在实际应用中,你需要处理异常并适当地关闭MongoClient,以避免资源泄漏: ```java mongoClient....

    MongoDB 在java中的应用 纯Java操作

    ### MongoDB在Java中的应用 #### 一、MongoDB简介与安装步骤 ...通过上述步骤,我们可以在Java环境中高效地使用MongoDB进行数据管理和操作。这种方式不仅提高了开发效率,还增强了应用程序的性能和可维护性。

    java操作mongodb存储文件实例

    将一系列图片文件存储到MongoDB中 java操作mongodb存储文件

    Mongodb + GridFS +Java 操作Mongodb中存储的文件

    在这个Java操作MongoDB中存储的文件实例中,我们将探讨如何利用GridFS API进行文件的存取。 首先,我们需要在Java项目中引入MongoDB的驱动库。目前,Java驱动通常使用的是MongoDB Java Driver,可以在Maven仓库中...

    java操作mongoDB(CRUD)

    Java操作MongoDB主要涉及到的是Java驱动程序与MongoDB数据库之间的交互,这涵盖了创建连接、执行CRUD(创建、读取、更新、删除)操作等一系列基本的数据库管理任务。MongoDB是一个流行的NoSQL数据库,以其灵活性、高...

    mongodb java 驱动支持jar 及其源码

    这个驱动程序允许Java应用程序连接到MongoDB服务器,执行CRUD(创建、读取、更新、删除)操作,进行查询、聚合以及其他高级数据库操作。例如,你可以使用`com.mongodb.client.MongoClients.create()`方法创建一个...

    mongoDB 操作 java源代码

    Java MongoDB 驱动是连接 Java 应用程序与 MongoDB 数据库的桥梁,它提供了丰富的 API 供开发者进行数据的增删改查以及其他操作。本压缩包包含的是 `mongodb-mongo-java-driver` 的源代码,版本号可能是 e6901ec,这...

    MongoDB java实现增删改查

    在Java开发中,我们可以使用MongoDB的Java驱动程序来实现对MongoDB数据库的增、删、改、查(CRUD)操作。以下是对这些核心功能的详细说明。 1. **增加(Create)** 要在MongoDB中插入数据,我们需要使用`...

    mongodb java driver 2.11

    MongoDB Java Driver 2.11是用于与MongoDB数据库进行交互的Java开发库,它提供了丰富的API,使得Java开发者可以方便地在应用程序中存取和管理MongoDB的数据。MongoDB是一款高性能、分布式、文档型的NoSQL数据库,它...

    mongodb_java_2.6_API

    MongoDB的Java驱动程序是Java开发者与MongoDB服务器通信的桥梁,它提供了丰富的API,使得在Java应用中执行CRUD(创建、读取、更新、删除)操作变得简单。2.6版本是历史版本,但仍然包含了许多核心功能,如连接管理...

    mongodb java 简单操作 win32 安装步骤

    在Windows 32位系统上安装MongoDB并进行Java操作涉及以下关键步骤: **一、MongoDB的Win32安装** 1. **下载MongoDB**:首先,你需要访问MongoDB官方网站(https://www.mongodb.com/)下载适用于Windows 32位系统的...

    MongoDb java driver 3.4.2

    MongoDB是一个流行的NoSQL数据库系统,而Java驱动程序则提供了在Java应用程序中操作MongoDB的接口。以下是关于MongoDB Java驱动3.4.2版本的一些关键知识点: 1. **驱动程序版本**:3.4.2是MongoDB Java驱动的一个...

    Java操作MongoDB实例

    Java操作MongoDB实例,压缩包内为完整项目源码,使用MyEclipse软件 见文:https://blog.csdn.net/qq_33427869/article/details/87270444

Global site tag (gtag.js) - Google Analytics