- 浏览: 125088 次
- 性别:
- 来自: 北京
最新评论
-
C_J:
有必要这么鸡冻咩?
编写自己的ClassLoader知识点 -
jason61719:
你这不是说了等于没说吗……就解析个loadClass(),谁不 ...
编写自己的ClassLoader知识点 -
jiming:
tedeyang 写道很好的改进,不过话说回来,mybatis ...
开源,从关注产品社区做起(ibatis3.x的最近一个issue展示) -
C_J:
独爱Java 写道好像实际用处并不是很大,只是多了解了有这个东 ...
Java内存模型笔记 -
独爱Java:
好像实际用处并不是很大,只是多了解了有这个东西而已。。。
Java内存模型笔记
A Quick Tour
Using the Java driver is very simple. First, be sure to include the driver jar mongo.jar in your classpath. The following code snippets come from the examples/QuickTour.java example code found in the driver.
Making A Connection
To make a connection to a MongoDB, you need to have at the minimum, the name of a database to connect to. The database doesn't have to exist - if it doesn't, MongoDB will create it for you.
Additionally, you can specify the server address and port when connecting. The following example shows three ways to connect to the database mydb on the local machine :
import com.mongodb.Mongo; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.DBCursor; Mongo m = new Mongo(); Mongo m = new Mongo( "localhost" ); Mongo m = new Mongo( "localhost" , 27017 ); DB db = m.getDB( "mydb" );
At this point, the db object will be a connection to a MongoDB server for the specified database. With it, you can do further operations.
Getting A List Of Collections
Each database has zero or more collections. You can retrieve a list of them from the db (and print out any that are there) :
Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println(s); }
and assuming that there are two collections, name and address, in the database, you would see
name address
as the output.
Inserting a Document
Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as
{ "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { x : 203, y : 102 } }
Notice that the above has an "inner" document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.
BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc);
Finding the First Document In A Collection using findOne()
To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.
DBObject myDoc = coll.findOne(); System.out.println(myDoc);
and you should see
{ "_id" : "49902cde5162504500b45c2c" , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102} , "_ns" : "testCollection"}
Note the _id and _ns elements have been added automatically by MongoDB to your document. Remember, MongoDB reserves element names that start with _ for internal use.
Adding Multiple Documents
In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be
{
"i" : value
}
and we can do this fairly efficiently in a loop
for (int i=0; i < 100; i++) { coll.insert(new BasicDBObject().append("i", i)); }
Notice that we can insert documents of different "shapes" into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free"
Counting Documents in A Collection
Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the getCount() method.
System.out.println(coll.getCount());
and it should print 101.
Using a Cursor to Get All the Documents
In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :
DBCursor cur = coll.find(); while(cur.hasNext()) { System.out.println(cur.next()); }
and that should print all 101 documents in the collection.
Getting A Single Document with A Query
We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;
BasicDBObject query = new BasicDBObject(); query.put("i", 71); cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
and it should just print just one document
{ "_id" : "49903677516250c1008d624e" , "i" : 71 , "_ns" : "testCollection"}
Getting A Set of Documents With a Query
We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write :
query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 50)); // e.g. find all where i > 50 cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
which should print the documents where i > 50. We could also get a range, say 20 < i <= 30 :
query = new BasicDBObject(); query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30 cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next()); }
Creating An Index
MongoDB supports indexes, and they are very easy to add on a collection. To create an index, you just specify the field that should be indexed, and specify if you want the index to be ascending (1) or descending (-1). The following creates an ascending index on the "i" field :
coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending
Getting a List of Indexes on a Collection
You can get a list of the indexes on a collection :
List<DBObject> list = coll.getIndexInfo(); for (DBObject o : list) { System.out.println(o); }
and you should see something like
{ "name" : "i_1" , "ns" : "mydb.testCollection" , "key" : { "i" : 1} , "_ns" : "system.indexes"}
Quick Tour of the Administrative Functions
Getting A List of Databases
You can get a list of the available databases:
Mongo m = new Mongo(); for (String s : m.getDatabaseNames()) { System.out.println(s); }
Dropping A Database
You can drop a database by name using the Mongo object:
m.dropDatabase("my_new_db");
发表评论
-
iOS入门(ongoing)
2012-09-13 11:32 1247Record it: The overview of ... -
Stuff about Android
2011-07-09 16:15 1032Foreword: long time ... -
JQuery初体验(Demo)
2011-05-22 13:43 1411Demo:Show <meta content ... -
Java内存模型笔记
2011-04-13 15:48 1508题记: 看到C/C++ ... -
Radiant_The Popular Ruby's CMS Demo篇
2011-04-02 14:49 1197题记: 上篇 记录我第一次安装Rodiant经过和 ... -
Radiant_The Popular Ruby’s CMS安装篇
2011-03-28 00:48 1235题记: 今天第一次参加JE的线下活动,robbin等 ... -
关于Azul 并发垃圾回收器
2011-03-26 14:40 1280题记: 总感觉JE讨论的帖子的东西都比较滞后,所以会 ... -
phpCMS & jQuery是我该做的(阉割了)
2011-02-27 23:02 81WD讲究以plugin挂载为结构,我需要构造一个p ... -
我的玩意:J2ME的Criteria初探
2011-01-20 21:59 982题记: 前几天跟初中同学聊天,他问我能不能做一个GP ... -
编写自己的ClassLoader知识点
2011-01-13 14:41 1841题记: 看到InfoQ关于ClassLoader的文 ... -
周末好玩,用短信控制你的计算机
2011-01-10 16:34 2913Snapshot: 详情 ... -
About Dock Plugin on Mac
2010-11-21 22:47 1430题记: 第一次接触MAC的开发..... ... -
可变hashcode的隐患和序列化安全
2010-10-25 00:55 1294可变hashcode的隐患 为识别对象,JDK ... -
体验OSGi(helloworld.jar)—富app的热拔插
2010-10-18 23:22 2378记得以前工作的时候,有天direct manager问 ... -
Getting Start on Mongodb
2010-08-26 01:29 1456题记: 最近老和同学聊到non-relational ... -
Java Media Framework本地玩转摄像头
2010-08-04 00:57 16931、简介The JavaTM Media Framework ... -
从WeakLogHandler应用看Java的引用、引用队列
2010-06-14 00:58 1473题记: 前几天讨论到WeakHashMap(这个是个弱引用的 ... -
《重构》读书笔记
2010-05-09 00:05 1005Martin Fowler于2003年出版 ... -
RPC之WebServices&RMI&JMS,phprpc框架?(待续)
2010-05-06 22:31 55前段时间写过基本的WebServices,也没再做深入 ... -
Java应用中的SQL注入攻击和防范
2010-04-24 01:06 6659说说自己对注入的 ...
相关推荐
MongoDB应用 Java应用 纯java mongodb操作 mongodb 通用dao
MongoDB实现增删改查,java程序驱动,复杂查询,源代码示例
MongoDB Java操作大全 源代码 实例
mongoDB java 驱动 mongoDB java 驱动 mongoDB java 驱动 mongoDB java 驱动
mongodb安装配置及java操作mongodb 三个word文档和一个Jar包,记录了使用说明
使用java向mongodb中插入数据 一、Linux安装mongodb 二、MongoDB客户端工具(MongoVUE)访问mongodb 三、通过Java操作MongoDB
Mongodb常用命令和java调用 比较好噢
解决连接池不够的问题,多连接的问题。适用于mongoDB项目开发,感兴趣可以下载使用,记得好评哦。欢迎在下方留言
MongoDB Java Driver 简单操作
MongoDB问文件存储,包括大文件存储
Java 操作Mongodb中存储的文件的实例
mongodb for java api 英文版
MongoDB on Kubernetes技术解决方案.pptx
MongoDBjava各版本驱动下载
MongoDB之Java使用例子,详细的增删改查例子,以及图片保存删除查询等~
注意:spring的不同版本与mongodb结合可能会有问题,自测:spring4.2.1结合mongodb会报错:**springframework.core.context.**service 此外,例子同时涉及: 1.例子中还说明了配置文件放在maven的src/main/java下与...
mongodb-java-driver-4.4.0.jar
mongoDB java driver api mongoDB java 驱动 所有类的api
java 操作mongodb代码,可直接运行成功,作为初学者非常实用。其中数据库是包含用户名和密码,用户名root ,密码root。
MongoDB spring hibernate java 集成demo