MongoDB Java
MongoDB Java
环境配置
在Java程序中如果要使用MongoDB,你需要确保已经安装了Java环境及MongoDB JDBC 驱动。
你可以参考本站的Java教程来安装Java程序。现在让我们来检测你是否安装了 MongoDB JDBC 驱动。
- 首先你必须下载mongo jar包,下载地址:https://github.com/mongodb/mongo-java-driver/downloads, 请确保下载最新版本。
- 你需要将mongo.jar包含在你的 classpath 中。。
连接数据库
连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库。
连接数据库的Java代码如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
现在,让我们来编译运行程序并创建数据库test。
你可以更加你的实际环境改变MongoDB JDBC驱动的路径。
本实例将MongoDB JDBC启动包 mongo-2.10.1.jar 放在本地目录下:
$javac MongoDBJDBC.java
$java -classpath ".:mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true
如果你使用的是Window系统,你可以按以下命令来编译执行程序:
$javac MongoDBJDBC.java
$java -classpath ".;mongo-2.10.1.jar" MongoDBJDBC
Connect to database successfully
Authentication: true
如果用户名及密码正确,则Authentication 的值为true。
创建集合
我们可以使用com.mongodb.DB类中的createCollection()来创建集合
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.createCollection("mycol");
System.out.println("Collection created successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection created successfully
获取集合
我们可以使用com.mongodb.DBCollection类的 getCollection() 方法来获取一个集合
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.createCollection("mycol");
System.out.println("Collection created successfully");
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection created successfully
Collection mycol selected successfully
插入文档
我们可以使用com.mongodb.DBCollection类的 insert() 方法来插入一个文档
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "//www.w3cschool.cn/mongodb/").
append("by", "w3cschool.cn");
coll.insert(doc);
System.out.println("Document inserted successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document inserted successfully
检索所有文档
我们可以使用com.mongodb.DBCollection类中的 find() 方法来获取集合中的所有文档。
此方法返回一个游标,所以你需要遍历这个游标。
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
DBCursor cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Inserted Document: 1
{
"_id" : ObjectId(7df78ad8902c),
"title": "MongoDB",
"description": "database",
"likes": 100,
"url": "//www.w3cschool.cn/mongodb/",
"by": "w3cschool.cn"
}
更新文档
你可以使用 com.mongodb.DBCollection 类中的 update() 方法来更新集合中的文档。
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到Mongodb服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到你的数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
DBObject updateDocument = cursor.next();
updateDocument.put("likes","200")
col1.update(updateDocument);
}
System.out.println("Document updated successfully");
cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println("Updated Document: "+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document updated successfully
Updated Document: 1
{
"_id" : ObjectId(7df78ad8902c),
"title": "MongoDB",
"description": "database",
"likes": 200,
"url": "//www.w3cschool.cn/mongodb/",
"by": "w3cschool.cn"
}
删除第一个文档
要删除集合中的第一个文档,首先你需要使用com.mongodb.DBCollection类中的 findOne()方法来获取第一个文档,然后使用remove 方法删除。
代码片段如下:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays; public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到Mongodb服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到你的数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
DBObject myDoc = coll.findOne();
col1.remove(myDoc);
DBCursor cursor = coll.find();
int i=1;
while (cursor.hasNext()) {
System.out.println("Inserted Document: "+i);
System.out.println(cursor.next());
i++;
}
System.out.println("Document deleted successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
编译运行以上程序,输出结果如下:
Connect to database successfully
Authentication: true
Collection mycol selected successfully
Document deleted successfully
你还可以使用 save(), limit(), skip(), sort() 等方法来操作MongoDB数据库。
MongoDB Java的更多相关文章
- MongoDB Java Driver操作指南
MongoDB为Java提供了非常丰富的API操作,相比关系型数据库,这种NoSQL本身的数据也有点面向对象的意思,所以对于Java来说,Mongo的数据结构更加友好. MongoDB在今年做了一次重 ...
- Mongodb Java Driver 参数配置解析
要正确使用Mongodb Java Driver,MongoClientOptions参数配置对数据库访问的并发性能影响极大. connectionsPerHost:与目标数据库能够建立的最大conn ...
- mongoDb +Java+springboot
前言 :mongoDb 是一种比较常用的非关系数据库,文档数据库, 格式为json ,redis 有五种格式. 1. 项目中要使用,这里简单做个示例.首先是连接mongoDB,用的最多的robomon ...
- BuguMongo是一个MongoDB Java开发框架,集成了DAO、Query、Lucene、GridFS等功能
http://code.google.com/p/bugumongo/ 简介 BuguMongo是一个MongoDB Java开发框架,它的主要功能包括: 基于注解的对象-文档映射(Object-Do ...
- 数据库.MongoDB.Java样例
1.先在MongoDB官网下载Java驱动包 MongoDB Java Driver: http://mongodb.github.io/mongo-java-driver/ JAR包下载列表 htt ...
- mongodb Java(八)
package com.mongodb.text; import java.net.UnknownHostException; import com.mongodb.DB; import com.mo ...
- MongoDB Java API操作很全的整理
MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,一般生产上建议以共享分片的形式来部署. 但是MongoDB官方也提供了其它语言的客户端操作API.如下图所示: 提供了C.C++ ...
- 三、Mongodb Java中的使用
添加maven依赖 <!--mongodb 驱动--> <dependency> <groupId>org.mongodb</groupId> < ...
- MongoDB Java连接---MongoDB基础用法(四)
MongoDB 连接 标准 URI 连接语法: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN ...
随机推荐
- CSS属性操作/下
CSS属性操作/下 1.伪类 anchor伪类 跟<a>/</a>有关:专用于控制链接的显示效果 a:link(没有接触过的链接),用于定义了链接的常规状态. a:hover( ...
- hive:导出数据记录中null被替换为\n的解决方案
在hive中,一般情况下通过 use my_hive_db; set hive.merge.mapfiles=true; set hive.merge.mapredfiles=true; ; ; in ...
- Bellman-Ford算法的改进---SPFA算法
传送门: Dijkstra Bellman-Ford SPFA Floyd 1.算法思想 Bellman-Ford算法时间复杂度比较高,在于Bellman-Ford需要递推n次,每次递推需要扫描所有的 ...
- 【FAQ系列】关于SQL_Errno:1677导致主从复制中断的思考和实践
1.简单介绍该错误发生的背景: 1) 数据库版本:MySQL5.7.19 2) 对一个大表修改字段类型DDL(将主键id int变为bigint),为了不影响主库业务,先在从库上执行DDL操作,然后通 ...
- Linux OpenGL 实践篇-1 OpenGL环境搭建
本次实践所使用环境为CentOS 7. 参考:http://www.xuebuyuan.com/1472808.html OpenGL开发环境搭建: 1.opengl库安装 opengl库使用mesa ...
- [LeetCode] Special Binary String 特殊的二进制字符串
Special binary strings are binary strings with the following two properties: The number of 0's is eq ...
- [LeetCode] Falling Squares 下落的方块
On an infinite number line (x-axis), we drop given squares in the order they are given. The i-th squ ...
- webpack构建react项目(一)
前言 下面是我们使用到技术栈: webpack + react + redux + react-router + react-thunk + ES6 + .... 注意事项: 建议使用npm5.X 或 ...
- spring mvc中的注解说明
注解扫描 context:component-scan 包扫描 <context:component-scan base-package="org.bdp"> < ...
- [HNOI 2011]卡农
Description 题库链接 在集合 \(S=\{1,2,...,n\}\) 中选出 \(m\) 个子集,满足三点性质: 所有选出的 \(m\) 个子集都不能为空. 所有选出的 \(m\) 个子集 ...