1、下载mongoDB的jar包,并引入到工程的CLASSPATH中下载:mongodb2.5驱动包下载

如果使用maven项目,最新的依赖如下:

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.2.0</version>
</dependency>

需要特别注意的是如果工程不是maven项目而是通过引入jar包的方式,那么在mongdb3.X之后,除了要引入mongo-java-driver之外,还需要手动引入bson和mongo-java-core的两个jar包,因为driver依赖这两个包,而且版本最好要一致,不然会报各种找不到jar包的错误。而如果是工程是maven项目那么就只需要引入mongodb的driver依赖即可,maven会自动去下载bson和mongo-java-core的依赖jar包。如下截图所示:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZcAAABLCAIAAAAzj126AAARfklEQVR4nO1dT28bxxXfj+CvUKfJUfBBB4Efw0cDOvTCY3LwIchNFnIKHIRRk9IFggA5RIgPBBS5YmUnLWpCBYwmchwf2BRELdtxagMrWZIVS6QlZ3tYkjvvzXszs8udJZd8PzwY1u78n3m/nfd2uC+IJg3NahBUap1xN8M3ZqCbYateb4WDv9qNpaUl5W+BJ7QbhY5zu7G01Gg7JPLSpu3t7e3t7SD/gkdDEATV5rgb4ROdWiUIgqnvZox2YymBda1POcBg9OFBtQtjsbBVt3ahn8bb5E8oiwkEAoEjhMUEAkG5kT+LbT8TERERKUiExURERMotwmIiIiLlliJY7O7mO7fqb93805ubn77515U3Nz5+48ZHb6x/eP7rq+fvbr4z9iEQEREptRTBYrfqb/32ev+3V/97ffKf1y/+dbZ38/Wz62dP/nz68Oqt+ltjHwIREZFSSxEsBvZif/z9xsdv/OWj8+sfnv/66u+may/WuTwfBIvN+M+VxSCYr63lVJouI5c/mdK5PD+V/RLxKEWw2IMne+99uvng6dHhy97hy96rV68OX3YfPD1679PNB0/2xj4E+UmRLFaQtq8sBgNULt/hkjUvBgnmljtsgatVWzLv/VpbrgQQF1dxX+AVKldpeJbuTilEmyl2BWZhsbOzM3cW27q3c/XLrcfh8e7hydFx9+i4e9LrHR33wsOTx+Hx1S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Wv6uiwulmwC+oQrF4aO7a2lNEUjuW9b8x+3Th8ODllqnVqNGnvUNaJkvhlGTE8APQcWI7xJhugB+Nutg0vg66+zE0Bv0iO54YBA+NnYIRJGkWsAN3OENXOxluhspjB09r7aS0Of6YYkkXRca4Eam8SskVx7zcOil2xqBluv+6atDAH0NO++w0dQqZgnkHcwh6UJd6B9YtdgqqJP7OKP43BxB6hv47rmJWvXYkEMrkeTHsmN3H1EUaTqQubQR0RGQ7ARWKw5r2MYuqGqpi8Nu611RqO/ps1xsEuT9HYRrcElm5oxKwH07H6xKIo0vUfvKPmwKrmHnhpc1Gg31YfCicSp8mq1K2nAf6NJj+Q2nSymYTQWS9KqWppy7+fQJP66jcUyv6XgP+ENQ6qQyOIXa/oIoOfIYsRbScdwBzmzGPxqfuZwB/pm0ikvW3vSahgcIZr0SG4uLJY9gBtNDlktSi2akZMGcTeZ2EhMhuRNCGlzO9TnnMTBogS3R3pby7GYm32Ht16cLcs5GS3+BWe4spgE0DPWPiwEBdCLJj2SmxOLaaaH7sFngg4h/zXy4BqLteS1vCggO2suzchi8d8V6IHC7VfOYrnopN595bFgHBbCGUU3gxoG9NqAfC7wWzRDa3hPI2SxwWW42/PAYhJAL58AetGkR3JzY7HBbdLJYmIxlK9/HgO/X2N9N4a8cWu5MHRsf42lmVgM06DaWaL5rjoJ2+QyLGTJXDMIgKQaJ6s8imFwIOjFscMLXi74tSglgF5uAfQkkpuK0bw4gnLCsLXLBal+zCcB9DJAvi+mQEhsFmE5+jE60qmSBNBLj5lmsU6tgt+we13OggnESK8fnDB2VZr6AHozzWIR8vDINmyWgH8P4g2ToErTHUDPxGIiIiK5SPGKPVNgWUwgEAhKAZbFfjkSERGZCSk7hMVERGZdyo6Yxf4P5aN/ea0W7xoAAAAASUVORK5CYII=" alt="" />

2、链接mongoDB服务器,并选择数据库
要建立MongoDB的连接,你只要指定要连接到的数据库就可以。这个数据库不一定存在,如果不存在,MongoDB会先为你建立这个库。同时,在连接时你也可以具体指定要连接到的网络地址和端口:
Mongo m = new Mongo();
// 或者
Mongo m = new Mongo( "localhost" );
// 或者
Mongo m = new Mongo( "localhost" , 27017 );
// 或者, to connect to a replica set, supply a seed list of members
Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
DB db = m.getDB("mydb" );

3、安全验证(可选)

 boolean auth = db.authenticate(userName, password);

4、获取集合列表。每个数据库都存在零个或多个集合,需要时你可以获得他们的列表:

Set<String> colls = db.getCollectionNames();

for (String s : colls) {
System.out.println(s);
}

5、获得一个集合。要获得某个特定集合,你可以指定集合的名字,并使用getCollection()方法:

DBCollection coll = db.getCollection("blog");

6、插入文档

mongodb存储JSON格式的文档,而在Java中表示这种数据格式的最简便的类就是Map了。MongoDB Java Driver中提供的BasicDBObject就是个Map(它继承自LinkedHashMap并实现DBObject接口),它会将Map中的数据转换成BSON格式传输到mongodb。

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

mongodb中每个插入的文档会产生个唯一标识_id。当调用coll.insert(doc);时,driver会检查其中是否有_id字段,如果没有则自动生成ObjectId实例来作为_id的值,这个ObjectId由4部分编码而成:当前时间、机器标识、进程号和自增的整数。insert函数也支持插入文档列表:insert(List list)

7、查询

find函数是查询集合的,它返回的DBCursor是DBObject的迭代器。如下代码:

BasicDBObject query = new BasicDBObject();
query.put("i", 71);
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}

8、建立索引

创建索引语句如:coll.createIndex(new BasicDBObject(“i”, 1)); ,其中i表示要索引的字段,1表示升序(-1表示降序)。可以看到,DBObject成为java客户端通用的结构表示。查看索引使用DBCollection.getIndexInfo()函数。

java客户端连接MongoDB数据库的简单使用的更多相关文章

  1. 【RabbitMQ】CentOS安装RabbitMQ,及简单的Java客户端连接

    在CentOS安装 因Rabbit MQ使用Erlang,所以需要先安装Erlang,安装过程中可能会遇到种种问题,可参考CentOS 6.5安装Erlang/OTP 17.0.然后就可以安装MQ了. ...

  2. atitit.客户端连接oracle数据库的方式总结

    客户端连接oracle数据库的方式总结 目录 Java程序连接一般使用jar驱动连接..... 桌面GUI一般采取c语言驱动oci.dll 直接连接... 间接连接(需要配置tns及其envi var ...

  3. 配置ORACLE 客户端连接到数据库

    --================================= -- 配置ORACLE 客户端连接到数据库 --================================= Oracle ...

  4. Elasticsearch - java客户端连接

    写在前面的话:读书破万卷,编码如有神-------------------------------------------------------------------- 最简单的在java客户端连 ...

  5. Zookeeper学习记录及Java客户端连接示例

    1. Zookeeper 1.1 简介 ZooKeeper is a centralized service for maintaining configuration information, na ...

  6. 远程客户端连接MysqL数据库太慢解决方案

    远程客户端连接MysqL数据库太慢解决方案局域网客户端访问mysql 连接慢问题解决. cd /etc/mysql vi my.conf [mysqld] skip-name-resolve 此选项禁 ...

  7. phoenix客户端连接hbase数据库报错:Traceback (most recent call last): File "bin/sqlline.py", line 27, in <module> import argparse ImportError: No module named argparse

    环境描述: 操作系统版本:CentOS release 6.5 (Final) phoenix版本:phoenix-4.10.0 hbase版本:hbase-1.2.6 现象描述: 通过phoenix ...

  8. 通过java客户端连接hbase 注意事项

    1.通过Java客户端连接Hbase,其中hbase通过zookeeper去管理,需要注意的是客户端端口. 通过在浏览器端输入地址查看:http://192.168.3.206:60010/maste ...

  9. Toad客户端连接Oracle数据库报错 ORA-12170:TNS:连接超时

    Oracle 客户端连接Oracle数据库报错   ORA-12170:TNS:连接超时  排错步骤: 1. 查看网络是否畅通:  打开cmd,ping数据库IP 2. 查看端口是否畅通: 打开cmd ...

随机推荐

  1. touch——移动端

    touch事件原生一定要用addEventListener来绑定 一.原生 touchstart:触摸开始时触发 touches:当前位于屏幕上所有手指的列表 event.touches.length ...

  2. PHP之数组遍历

    数组在PHP中是一个非常强大的武器,用起来方便.容易,由于使用起来异常灵活,用它就可以实现数据结构中的链表.栈.队列.堆以及所谓的字典.集合等,也可以转换成XML格式. 1.使用for for语句遍历 ...

  3. nvl()函数

    Oracle里面的nvl()函数 Nvl(字段名,0):如果你某个字段为空,但是你想让这个字段显示0,nvl(字段名,0) ,就是当你选择出来的时候,这个字段虽然为空,但是显示的是0,当然这个0也可以 ...

  4. Microsoft Visual Studio 2013 Update 2 离线安装程序

    ☆ 微软官网地址:☆ http://www.microsoft.com/zh-cn/download/details.aspx?id=42665☆ 离线安装程序 直接下载链接:☆ Microsoft ...

  5. 快速登录IRC网络聊天室

    随便起个NickName,进行人机验证,然后点击Connect进去就可以咯.

  6. ### About Multi-Object Tracking

    点击查看Evernote原文. #@author: gr #@date: 2014-10-17 #@email: forgerui@gmail.com Multi_Object Tracking Fr ...

  7. ###学习《Effective C++》

    开源中国. #@date: 2014-06-16 #@author: gerui #@email: forgerui@gmail.com 前几天买了好几本书,其中有一本是<Effective C ...

  8. C--指针函数,static

    (*p)是固定写法,代表指针的变量P将来是指向函数 void (*p)(); p=test;//指针变量P指向了test函数 函数名test代表函数地址 //同等调用test()函数 (*p)(); ...

  9. javascript form 第22节

    <html> <head> <title>Form对象</title> </style> <script type="tex ...

  10. [PR & ML 5] [Introduction] Decision Theory