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 ...
随机推荐
- python Django知识点总结
python Django知识点总结 一.Django创建项目: CMD 终端:Django_admin startproject sitename(文件名) 其他常用命令: 其他常用命令: 通过类创 ...
- JavaScript是如何面向对象的
一.引言 在16年的10月份,在校内双选会找前端实习的时候,hr问了一个问题:JavaScript的面向对象理解吗?我张口就说"JavaScript是基于原型的!".然后就没什么好 ...
- CMDB开发
浅谈ITIL TIL即IT基础架构库(Information Technology Infrastructure Library, ITIL,信息技术基础架构库)由英国政府部门CCTA(Central ...
- UVA-562 Dividing coins---01背包+平分钱币
题目链接: https://vjudge.net/problem/UVA-562 题目大意: 给定n个硬币,要求将这些硬币平分以使两个人获得的钱尽量多,求两个人分到的钱最小差值 思路: 它所给出的n个 ...
- HDU-1850 Being a Good Boy in Spring Festival---尼姆博奕的运用
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1850 题目大意: 中文题: 思路: 传送门:尼姆博奕 #include<iostream> ...
- Python open()函数文件打开、读、写操作详解
一.Python open()函数文件打开操作 打开文件会用到open函数,标准的python打开文件语法如下:open(name[,mode[,buffering]])open函数的文件名是必须的, ...
- phpmyadmin设置编码和字符集gbk或utf8_导入中文乱码解决方法
一.phpmyadmin设置新建数据库的默认编码为utf8编码的方法 1:新建数据库 my_db 2:使用sql语句 set character_set_server=utf8; //设置默认新 ...
- jacascript 函数声明、函数表达式与声明提升(hoisting机制)
前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 声明.定义.初始化 声明的意思是宣称一个变量名的存在,定义则为这个变量分配存储空间,初始化则是给该变量名的 ...
- CentOS 6.8下二级域名及目录的绑定
二级域名对应目录的绑定: 第一步: 开启mod_rewrite模块,默认是开启的,这里可以查下是否开启 终端输入:vim /etc/httpd/conf/httpd.conf 回车 查看188行:L ...
- laydate 日期格式为yyyy 或yyyy-MM时,出现错误Uncaught TypeError: Cannot read property 'length' of undefined
这个改起比较麻烦,没有深究,简单兼容了yyyy 和yyyy-MM,其他格式可能还是会有错误.替换Dates.check方法. //检测日期是否合法 Dates.check = function(){ ...