Java:连接MongoDB的一些示例

是这样的

首先,这篇主要面向有一些MongoDB经验的.
本来打算在很久之前就整理一下Java连接MongoDB的内容,但是一拖再拖只好现在写了,希望还不算太迟.由于安装实在太过于简单了,所以这里直接讲怎么连接.

1.连接到MongoDB

连接前首先要导入以下两个包,可以在这里找到(点我,点我,快点我啊):

  • bson文件夹下面的:bson-*.jar [*=版本]
  • mongo-java-driver文件夹下面的:mongo-java-driver-*.jar[*=版本]

两个的版本最好是一样的,避免出现问题.

在这里使用的bson和mongo-java-driver版本均是:3.0.1

下面是连接的源码[一定要先启动MongoDB服务器,否则报错!]:


//连接到mongodb.
MongoClient mongoClient = new MongoClient();
/*
可以上面那样连接,也可以像下面这样去连接[来自官方文档]:
MongoClient mongoClient1 = new MongoClient();
MongoClient mongoClient1 = new MongoClient("localhost");
MongoClient mongoClient2 = new MongoClient("localhost", 27017);
MongoClient mongoClient4 = new MongoClient(new ServerAddress("localhost"));
MongoClient mongoClient5 = new MongoClient(new ServerAddress("localhost"), new MongoClientOptions.Builder().build());

或者:
MongoClient mongoClient = new MongoClient(Arrays.asList(
new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
*/
MongoDatabase db = mongoClient.getDatabase("test");
System.out.println(db);
// end.

运行结果如下:


May 14, 2015 9:08:03 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
com.mongodb.MongoDatabaseImpl@35f983a6
Process finished with exit code 0

mongodb
image-2278

2.插入数据

插入数据的时候要用到上面的源码,并且要确认MongoDB真实可用[输入命令mongo试试即可].


//连接到mongodb.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
// end.
//--------------------------
//插入一个文档.
db.getCollection("restaurants").insertOne(new Document("address"
, new Document().append("street", "2 Avenue")
.append("street", "2 Avenue")
.append("zipcode", "10075")
.append("building", "1480")
.append("coord", asList(-73.9557413, 40.7720266)))
.append("borough", "Manhattan")
.append("cuisine", "Italian")
.append("grades", asList(
new Document().append("date", "2014-10-01T00:00:00")
.append("grade", "A")
.append("score", "11"),
new Document().append("date", LocalDateTime.now().toString())
.append("grade", "B")
))
.append("name", "test").append("restaurant_id", "41704620"));

insertOne(),运行成功之后是没有提示的!!

3.查询结果

查询有多种条件过滤,更多可以参考文档.


//连接到mongodb.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
// end.
//--------------------------
FindIterable iterable =db.getCollection("restaurants").find(eq("borough", "Manhattan"));
//下面是其他查询方式.[这些方式都可以用new Document替代,但是这样写更加简洁.]
/*
db.getCollection("restaurants").find(eq("borough", "Manhattan"));
db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
db.getCollection("restaurants").find(gt("grades.score", 30));
db.getCollection("restaurants").find(lt("grades.score", 10));
db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
*/
iterable.forEach(new Block() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});

下面是我的查询结果:


Document{{_id=5554bfa96204f509fa8578c3, address=Document{{street=2 Avenue, zipcode=10075, building=1480, coord=[-73.9557413, 40.7720266]}}, borough=Manhattan, cuisine=Italian, grades=[Document{{date=2014-10-01T00:00:00, grade=A, score=11}}, Document{{date=2015-05-14T23:30:49.132, grade=B}}], name=test, restaurant_id=41704620}}

4.更新数据

更新数据,源码如下:


//连接到mongodb.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
// end.
//--------------------------更新一条数据,返回更新条数
db.getCollection("restaurants").updateOne(
new Document("name","Juni"),
new Document("$set",new Document("cuisine",
"American (Bew)")).append(
"$currentDate",new Document
("lastModified",true)));
/*
更新多条数据,使用下面的代码[返回更新条数]:
db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
new Document("$set", new Document("cuisine", "Category To Be Determined"))
.append("$currentDate", new Document("lastModified", true)));
*/

除了上面更新,也可以使用替换(替换将覆盖原文档!!).

db.getCollection("restaurants").replaceOne(new Document("restaurant_id", "41704620"),
new Document("address",
new Document()
.append("street", "2 Avenue")
.append("zipcode", "10075")
.append("building", "1480")
.append("coord", asList(-73.9557413, 40.7720266)))
.append("name", "Vella 2"));

5.删除数据

!!!删除前,一定要做好备份!!

一共有三个删除方式:

  • 1.删除文档
  • 2.删除全部文档
  • 3.删除集合


//返回删除数
db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));
/*
删除全部文档[返回删除数]:
db.getCollection("restaurants").deleteMany(new Document());

删除一个集合:

db.getCollection("restaurants").drop();
*/

6.聚合查询

下面是一个例子,里面的[$group]、[$sum]均是MongoDB的关键字,可以查阅相应文档获取更多.


//实在不好意思,我也是写到这才发现toJson返回的数据是格式化过的..
AggregateIterable iterable = db.getCollection("restaurants").aggregate(asList(
new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));
iterable.forEach(new Block(){
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
});

7.索引

下面是两个创建索引的方式:


db.getCollection("restaurants").createIndex(new Document("cuisine", 1));//创建单个索引

//------------

db.getCollection("restaurants").createIndex(new Document("cuisine", 1).append("address.zipcode", 1));//创建多个索引

源码

上面所有示例的源码.


package com.mongodemos;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.time.LocalDateTime;

import static com.mongodb.client.model.Filters.eq;
import static java.util.Arrays.asList;

/**
* MongoDB -Java常用操作.
*
* @author puruidong
* @version 2015.05.15 00:45
*/
public class Main {
public static void main(String[] args) {
//连接到mongodb.
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
// end.
//--------------------------
//看相应方法调取.
}

/**
* 聚合查询.
*
* @param db
*/
private static void aggFind(MongoDatabase db) {
AggregateIterable iterable = db.getCollection("restaurants").aggregate(asList(
new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));
iterable.forEach(new Block() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
});
}

/**
* 删除数据.!慎用!!
*
* @param db
* @return
*/
private static long deleteData(MongoDatabase db) {
//返回删除数
return db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan")).getDeletedCount();
/*
删除全部文档[返回删除数]:
db.getCollection("restaurants").deleteMany(new Document());

删除一个集合:

db.getCollection("restaurants").drop();
*/

}

/**
* 更新文档数据
*
* @param db
* @return
*/
private static long updateData(MongoDatabase db) {
return db.getCollection("restaurants").updateOne(
new Document("name", "Juni"),
new Document("$set", new Document("cuisine",
"American (Bew)")).append(
"$currentDate", new Document
("lastModified", true))).getModifiedCount();
/*
更新多条数据,使用下面的代码[返回更新条数]:

db.getCollection("restaurants").updateMany(new Document("address.zipcode", "10016").append("cuisine", "Other"),
new Document("$set", new Document("cuisine", "Category To Be Determined"))
.append("$currentDate", new Document("lastModified", true)));

替换使用下面的代码[替换会覆盖原有数据]:

db.getCollection("restaurants").replaceOne(
new Document("restaurant_id","41704620"),
new Document("address",new Document()
.append("street","2 Avenue")
.append("zipcode","1007")
.append("building","1480")
.append("coord",asList(-73.9557413,40.7720266))
.append("name","Vella 2"))
);

*/

}

/**
* 查询数据.
*
* @param db
*/
private static void findData(MongoDatabase db) {
FindIterable iterable = db.getCollection("restaurants").find(eq("borough", "Manhattan"));
//下面是其他查询方式.[这些方式都可以用new Document替代,但是这样写更加简洁.]
/*
db.getCollection("restaurants").find(eq("borough", "Manhattan"));
db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
db.getCollection("restaurants").find(gt("grades.score", 30));
db.getCollection("restaurants").find(lt("grades.score", 10));
db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
db.getCollection("restaurants").find(or(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
db.getCollection("restaurants").find().sort(ascending("borough", "address.zipcode"));
*/
iterable.forEach(new Block() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
}

/**
* 通过db对象插入一个集合.
*
* @param db
*/
private static void insertData(MongoDatabase db) {
//插入一个文档.
db.getCollection("restaurants").insertOne(new Document("address"
, new Document().append("street", "2 Avenue")
.append("street", "2 Avenue")
.append("zipcode", "10075")
.append("building", "1480")
.append("coord", asList(-73.9557413, 40.7720266)))
.append("borough", "Manhattan")
.append("cuisine", "Italian")
.append("grades", asList(
new Document().append("date", "2014-10-01T00:00:00")
.append("grade", "A")
.append("score", "11"),
new Document().append("date", LocalDateTime.now().toString())
.append("grade", "B")
))
.append("name", "test").append("restaurant_id", "41704620"));

}
}

嗯,暂时就这些.如果有不明白的可以网上搜索一下MongoDB教程.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据