MongoDB 3.X JAVA基本操作
对Collection的操作
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import org.bson.Document; import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel; import static com.mongodb.client.model.Filters.gt; /***/
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.lt; public class MongoDBJDBC { @SuppressWarnings("resource")
public static void main(String[] args) {
try {
/** 直接登录 */
// To directly connect to a single MongoDB server.
// (this will not auto-discover the primary even if it's a member of a replica set)
/*
MongoClient mongoClient = new MongoClient("192.168.253.10", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("dsp");
System.out.println("Connect to database successfully!");
*/ /** 使用URI连接信息连接 */
/*
MongoClientURI connectionString = new MongoClientURI("mongodb://192.168.253.10:27017,192.168.253.20:27018,192.168.253.30:27019");
MongoClient mongoClient = new MongoClient(connectionString);
*/ /** Replica Set 认证登录 */
// to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
// 数据库URI(两个参数分别为:服务器地址、端口)
ServerAddress serverAddress = new ServerAddress("192.168.253.10", 27017);
List<ServerAddress> addressList = new ArrayList<ServerAddress>();
addressList.add(serverAddress);
// 认证信息(三个参数分别为:用户名、数据库名称、密码)
MongoCredential credential = MongoCredential.createScramSha1Credential("dsp", "dsp", "shi".toCharArray());
List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
credentialList.add(credential);
// 根据URI和认证信息获取数据库连接
MongoClient mongoClient = new MongoClient(addressList, credentialList); /** 切换数据库 */
MongoDatabase mongoDatabase = mongoClient.getDatabase("dsp");
/** 切换到需要操作的集合 */
MongoCollection collection = mongoDatabase.getCollection("col"); /** 插入文档 */
// 创建文档 org.bson.Document对象,参数为K:V格式
// 创建文档集合List<Document>
// 将文档集合插入数据库集合中collection.insertMany(List<Document>),插入单个文档可以用collection.insertOne(Document)
/*
List<Document> docList = new ArrayList<Document>();
for (int idx = 0; idx < 10; ++idx) {
Document doc = new Document("title", "MongoDB" + idx).
append("desc", "数据库" + idx).
append("likes", 100 + idx * 10).
append("by", "dsp" + idx);
docList.add(doc);
}
collection.insertMany(docList);
*/ /** 更新文档 */
/*
UpdateResult updateResult = collection.updateMany(and(gt("likes", 90), lt("likes", 110)), new Document("$set", new Document("likes", 30)));
updateResult.getMatchedCount();
updateResult.getUpsertedId();
updateResult.getModifiedCount();
*/ /** 删除文档 */
/*
DeleteResult deleteResult = collection.deleteMany(Filters.eq("likes", 30));
System.out.println("本次删除 " + deleteResult.getDeletedCount() + " 条记录!");
*/ /** 检索文档 */
/*
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
try {
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next().toJson());
}
} finally {
mongoCursor.close();
}
*/ // 查询过滤器
/*
Document myDoc = (Document) collection.find(eq("likes", 10)).first();
System.out.println(myDoc.toJson());
*/ /** 使用范围查询获取一个较大的子集 */
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(Document doc) {
System.out.println(doc.toJson());
}
};
// 过滤 likes > 10
// collection.find(gt("likes", 10)).forEach(printBlock);
// 过滤 10 <= likes <= 100
// collection.find(and(Filters.gte("likes", 10), Filters.lte("likes", 100))).forEach(printBlock); /** 排序 */
// collection.find(Filters.exists("likes")).sort(Sorts.descending("likes")).limit(2).forEach(printBlock); /** Projection */
// Document myDoc = (Document) collection.find().projection(Projections.excludeId()).first();
// System.out.println(myDoc.toJson()); /** ordered bulk writes */
List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
writes.add(new InsertOneModel<Document>(new Document("_id", 13)));
writes.add(new InsertOneModel<Document>(new Document("_id", 14)));
writes.add(new InsertOneModel<Document>(new Document("_id", 15)));
writes.add(new UpdateOneModel<Document>(new Document("_id", 10), new Document("$set", new Document("x", 101010))));
writes.add(new DeleteOneModel<Document>(new Document("_id", 11)));
writes.add(new ReplaceOneModel<Document>(new Document("_id", 12), new Document("_id", 12).append("x", 121212)));
// bulkWrite默认BulkWriteOptions
// collection.bulkWrite(writes);
// collection.find().forEach(printBlock);
//
// collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
// collection.find().forEach(printBlock); /** drop集合 */
// collection.drop(); /** drop数据库 */
// mongoDatabase.drop();
} catch (Exception e) {
System.err.println(e.getClass().getName() + " : " + e.getMessage());
} finally {
// 防止意外,关闭数据库连接
// mongoClient.close();
}
} }
参考:
https://github.com/mongodb/mongo-java-driver/blob/3.0.x/driver/src/examples/tour/QuickTour.java
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/
:)
MongoDB 3.X JAVA基本操作的更多相关文章
- 4.0.3的mongodb 安装和java使用
一 整合 由于本人的码云太多太乱了,于是决定一个一个的整合到一个springboot项目里面. 附上自己的github项目地址 https://github.com/247292980/spring- ...
- hbase的Java基本操作
hbase的Java基本操作 建表,建列簇操作 private static Connection connection; private static Admin admin; public sta ...
- MongoDB的ObjectId和基本操作增删改查(3)
ObjectId 基本操作增删改查 增: insert 介绍: mongodb存储的是文档,. 文档是json格式的对象. 语法: db.collectionName.insert(document) ...
- MongoDB的安装和基本操作
一.使用前的准备(windows下的安装) 1.下载 目前MongoDB的官网不知道问什么不能进行下载了,但是可以在MongoDB中文论坛进行下载, 地址如下:http://www.mongoing ...
- 【MongoDB数据库】Java MongoDB CRUD Example
上一页告诉我们MongoDB 命令入门初探,本篇blog将基于上一篇blog所建立的数据库和表完毕一个简单的Java MongoDB CRUD Example.利用Java连接MongoDB数据库,并 ...
- MongoDB文档的基本操作
1. MongoDB的安装方法 (1)下载MongoDB 相应的版本: (2)设置数据文件和日志文件的存放目录: (3)启动MongoDB服务: (4)将MongoDB作为服务启动. 2. Mongo ...
- MongoDB分页的Java实现和分页需求的思考
前言 传统关系数据库中都提供了基于row number的分页功能,切换MongoDB后,想要实现分页,则需要修改一下思路. 传统分页思路 假设一页大小为10条.则 //page 1 1-10 //pa ...
- 学习MongoDB 七: MongoDB索引(索引基本操作)(一)
一.简介 在MongoDB建立索引能提高查询效率,只需要扫描索引只存储的这个集合的一小部分,并只把这小部分加载到内存中,效率大大的提高,如果没有建立索引,在查询时,MongoDB必须执行全表扫描,在数 ...
- Java操作Mongodb 保存/读取java对象到/从mongodb
从http://central.maven.org/maven2/org/mongodb/mongo-java-driver/选择一个版本进行下载,这里选择的是3.0.0版本,具体下载以下jar包: ...
随机推荐
- (转)在Docker中运行Java:为了防止失败,你需要知道这些
转自:https://mp.weixin.qq.com/s?__biz=MzA5OTAyNzQ2OA==&mid=2649693848&idx=1&sn=4e9ef7e2a9d ...
- Spark(Hive) SQL中UDF的使用(Python)【转】
相对于使用MapReduce或者Spark Application的方式进行数据分析,使用Hive SQL或Spark SQL能为我们省去不少的代码工作量,而Hive SQL或Spark SQL本身内 ...
- Ant编译android程序
http://blog.csdn.net/xyz_lmn/article/details/7268582 这一篇主要做了创建android项目.update已存在项目.ant编译项目. 一,准备ant ...
- 6款漂亮HTML CSS样式用户留言表单
如今我们的网站.页面更加需要注重细节,不论是字体的样式.还是图片的分辨率清晰度都会影响到用户的访问体验和PV,以及用户以后是否会回访我们的网站/博客.如果有时间的时候,老左也会浏览和阅读相关的前端网站 ...
- GBDT 迭代决策树
GBDT(Gradient Boosting Decision Tree) 又叫 MART(Multiple Additive Regression Tree),是一种迭代的决策树算法,该算法由多棵决 ...
- linespace函数
numpy.linspace numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)[source] ...
- poj1753(位运算压缩状态+bfs)
题意:有个4*4的棋盘,上面摆着黑棋和白旗,b代表黑棋,w代表白棋,现在有一种操作,如果你想要改变某一个棋子的颜色,那么它周围(前后左右)棋子的颜色都会被改变(白变成黑,黑变成白),问你将所有棋子变成 ...
- Emacs文件命令
[文件]----------------------------------------C-x C-f 读取文件到Emacs C-x r 只读的方式打开一个文件C-x C-q 清除一个窗口的只读属性 ...
- MySQL 中联合查询效率分析
目前我有两个表,一个keywords和一个news表.keyword存放关键词是从news中提取,通newsid进行关联,两表关系如图: keywords中存有20万条数据,news中有2万条数据,现 ...
- C#学习笔记(16)——C#中重写(override)和覆盖(new)的区别
说明(2017-7-17 23:04:45): 原文: C#中重写(override)和覆盖(new)的区别 重写 用关键字 virtual 修饰的方法,叫虚方法.可以在子类中用override 声明 ...