- 浏览: 1012224 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (826)
- 硬件 (8)
- 软件 (24)
- 软件工程 (34)
- JAVA (229)
- C/C++/C# (77)
- JavaScript (8)
- PHP (1)
- Ruby (3)
- MySQL (14)
- 数据库 (19)
- 心情记事 (12)
- 团队管理 (19)
- Hadoop (1)
- spring (22)
- mybatis(ibatis) (7)
- tomcat (16)
- velocity (0)
- 系统架构 (6)
- JMX (8)
- proxool (1)
- 开发工具 (16)
- python (10)
- JVM (27)
- servlet (5)
- JMS (26)
- ant (2)
- 设计模式 (5)
- 智力题 (2)
- 面试题收集 (1)
- 孙子兵法 (16)
- 测试 (1)
- 数据结构 (7)
- 算法 (22)
- Android (11)
- 汽车驾驶 (1)
- lucene (1)
- memcache (12)
- 技术架构 (7)
- OTP-Erlang (7)
- memcached (17)
- redis (20)
- 浏览器插件 (3)
- sqlite (3)
- Heritrix (9)
- Java线程 (1)
- scala (0)
- Mina (6)
- 汇编 (2)
- Netty (15)
- libevent (0)
- CentOS (12)
- mongod (5)
- mac os (0)
最新评论
-
kingasdfg:
你这里面存在一个错误添加多个任务 应该是这样的 /** * ...
Quartz的任务的临时启动和暂停和恢复【转】 -
kyzeng:
纠正一个错误,long型对应的符号是J,不是L。
Jni中C++和Java的参数传递 -
zhaohaolin:
抱歉,兄弟,只是留下作记录,方便学习,如果觉得资料不好,可以到 ...
netty的个人使用心得【转】 -
cccoooccooco:
谢谢!自己一直以为虚机得使用网线才可以与主机连接呢。。
主机网卡无网线连接与虚拟机通信 -
yuqilin001:
要转别人的东西,请转清楚点嘛,少了这么多类,误人子弟
netty的个人使用心得【转】
使用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}})
发表评论
-
调试jdk中的源码,查看jdk局部变量
2013-06-15 23:30 1050调试jdk中的源码,查看jdk局部变量 2012-04 ... -
Eclipse快捷键 10个最有用的快捷键<转>
2013-04-11 23:28 1072Eclipse中10个最有用的快捷键组合 一个Eclip ... -
Lucene 3.6 中文分词、分页查询、高亮显示等
2012-12-09 23:35 18151、准备工作 下载lucene 3.6.1 : htt ... -
Maven实战(九)——打包的技巧(转)
2012-10-12 00:41 934“打包“这个词听起 ... -
基于Maven的web工程如何配置嵌入式Jetty Server开发调试环境(转)
2012-10-12 00:28 9231、首先在web工程的POM文件里添加依赖jar包如下: ... -
轻轻松松学Solr(1)--概述及安装[转]
2012-09-18 14:59 993概述 这段时间对企 ... -
分析Netty工作流程[转]
2012-09-04 19:02 886下面以Netty中Echo的例 ... -
让eclipse在ubuntu下面好看一点
2012-03-27 10:17 915<p> </p> <h1 cla ... -
zookeeper安装和应用场合(名字,配置,锁,队列,集群管理)[转]
2012-01-12 17:59 1647安装和配置详解 本文 ... -
Jakarta-Common-BeanUtils使用笔记[转]
2012-01-10 14:13 1153Jakarta-Common-BeanUtils ... -
一个关于Java Thread wait(),notify()的实用例【转】
2012-01-07 16:05 1020///// // ProducerConsume ... -
Java基础:Java中的 assert 关键字解析【转】
2012-01-06 19:50 1057J2SE 1.4在语言上提供了 ... -
一篇不错的讲解Java异常的文章(转载)----感觉很不错,读了以后很有启发[转]
2012-01-06 15:02 1263六种异常处理的陋习 ... -
如何解决HP QC(Quality Center)在Windows 7下不能工作的问题
2011-12-26 10:48 1577HP QC(Quantity Center) 是一款不错的测 ... -
JAVA读写文件,中文乱码 【转】
2011-12-19 23:43 2117最近在做HTML静态生成,需要从硬盘上把模版文件的内容读出来。 ... -
Java 6 JVM参数选项大全(中文版)【转】
2011-12-19 19:51 969Java 6 JVM参数选项大全(中文版) 作者 ... -
使用assembly plugin实现自定义打包【转】
2011-12-13 01:58 968在上一篇文章中,讨论到在对maven的机制不熟悉的情况下,为了 ... -
使用maven ant task实现非标准打包[转]
2011-12-13 01:56 1046maven很强大,但是总有些事情干起来不是得心应手,没有使用a ... -
Java日期转换SimpleDateFormat格式大全【转】
2011-12-08 20:22 130924小时制时间 显示: public clas ... -
使用Spring的表单标签库
2011-11-22 20:08 106913.9. 使用Spring的 ...
相关推荐
### MongoDB Java Driver 简单操作详解 #### 一、简介 MongoDB 是一款非常流行的文档型数据库系统,因其灵活性和高性能而被广泛应用于多种场景之中。为了方便开发者使用 Java 进行开发,MongoDB 提供了官方的 Java ...
MongoDB Java驱动是Java开发者与MongoDB数据库交互的重要工具,它允许Java应用程序通过标准的Java API来执行查询、插入、更新和删除等操作。在Java中使用MongoDB,首先需要安装并配置对应的驱动版本,以确保与正在...
本资料包“MongoDB Java操作大全 源代码 实例”将深入探讨如何使用Java API进行MongoDB的操作。 1. **连接MongoDB** 在Java中,首先需要通过`MongoClient`类建立到MongoDB服务器的连接。例如: ```java ...
本篇将详细介绍如何使用Java连接MongoDB,以及进行基本的数据操作:创建集合、添加文档、修改文档、查询文档和删除文档。 首先,为了连接MongoDB,我们需要引入MongoDB的Java驱动程序依赖。在Maven项目中,可以在...
MongoDB是一个高性能、开源、无模式的文档型数据库,而Java驱动API则为Java开发者提供了一个直观且强大的接口来操作MongoDB。 首先,让我们了解一下MongoDB Java驱动API的基本结构和核心概念: 1. **MongoClient**...
### MongoDB Java API 使用详解 #### 一、Java 驱动简介与一致性 MongoDB 的 Java 驱动是...这些知识点涵盖了大部分常见的 MongoDB 应用场景,可以帮助初学者快速上手并熟练掌握如何使用 Java 驱动进行数据库操作。
MongoDB Java驱动程序是Java开发者用来与MongoDB数据库进行交互的一种关键工具。它提供了一组丰富的API,使得在Java应用程序中执行CRUD(创建、读取、更新、删除)操作变得简单而高效。MongoDB是一个分布式文档存储...
以上就是Java操作MongoDB的基本步骤。这个“mongodb_helloworld”项目应该包含示例代码,帮助初学者快速上手。记得在实际应用中,你需要处理异常并适当地关闭MongoClient,以避免资源泄漏: ```java mongoClient....
### MongoDB在Java中的应用 #### 一、MongoDB简介与安装步骤 ...通过上述步骤,我们可以在Java环境中高效地使用MongoDB进行数据管理和操作。这种方式不仅提高了开发效率,还增强了应用程序的性能和可维护性。
将一系列图片文件存储到MongoDB中 java操作mongodb存储文件
在这个Java操作MongoDB中存储的文件实例中,我们将探讨如何利用GridFS API进行文件的存取。 首先,我们需要在Java项目中引入MongoDB的驱动库。目前,Java驱动通常使用的是MongoDB Java Driver,可以在Maven仓库中...
Java操作MongoDB主要涉及到的是Java驱动程序与MongoDB数据库之间的交互,这涵盖了创建连接、执行CRUD(创建、读取、更新、删除)操作等一系列基本的数据库管理任务。MongoDB是一个流行的NoSQL数据库,以其灵活性、高...
这个驱动程序允许Java应用程序连接到MongoDB服务器,执行CRUD(创建、读取、更新、删除)操作,进行查询、聚合以及其他高级数据库操作。例如,你可以使用`com.mongodb.client.MongoClients.create()`方法创建一个...
Java MongoDB 驱动是连接 Java 应用程序与 MongoDB 数据库的桥梁,它提供了丰富的 API 供开发者进行数据的增删改查以及其他操作。本压缩包包含的是 `mongodb-mongo-java-driver` 的源代码,版本号可能是 e6901ec,这...
在Java开发中,我们可以使用MongoDB的Java驱动程序来实现对MongoDB数据库的增、删、改、查(CRUD)操作。以下是对这些核心功能的详细说明。 1. **增加(Create)** 要在MongoDB中插入数据,我们需要使用`...
MongoDB Java Driver 2.11是用于与MongoDB数据库进行交互的Java开发库,它提供了丰富的API,使得Java开发者可以方便地在应用程序中存取和管理MongoDB的数据。MongoDB是一款高性能、分布式、文档型的NoSQL数据库,它...
MongoDB的Java驱动程序是Java开发者与MongoDB服务器通信的桥梁,它提供了丰富的API,使得在Java应用中执行CRUD(创建、读取、更新、删除)操作变得简单。2.6版本是历史版本,但仍然包含了许多核心功能,如连接管理...
在Windows 32位系统上安装MongoDB并进行Java操作涉及以下关键步骤: **一、MongoDB的Win32安装** 1. **下载MongoDB**:首先,你需要访问MongoDB官方网站(https://www.mongodb.com/)下载适用于Windows 32位系统的...
MongoDB是一个流行的NoSQL数据库系统,而Java驱动程序则提供了在Java应用程序中操作MongoDB的接口。以下是关于MongoDB Java驱动3.4.2版本的一些关键知识点: 1. **驱动程序版本**:3.4.2是MongoDB Java驱动的一个...
Java操作MongoDB实例,压缩包内为完整项目源码,使用MyEclipse软件 见文:https://blog.csdn.net/qq_33427869/article/details/87270444