mongodb QuickStart Demo
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
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 org.bson.Document; import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Filters.gt;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lt;
import static com.mongodb.client.model.Filters.lte;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Updates.inc;
import static com.mongodb.client.model.Updates.set;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
public class QuickTour {
/**
* Run this main method to see the output of this quick example.
*
* @param args takes an optional single argument for the connection string
*/
public static void main(final String[] args) throws Exception{
MongoClient mongoClient; if (args.length == 0) {
// connect to the local database server
mongoClient = MongoClients.create();
} else {
mongoClient = MongoClients.create(args[0]);
} // get handle to "mydb" database
MongoDatabase database = mongoClient.getDatabase("mydb"); // get a handle to the "test" collection
MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it
collection.drop(); // make a document and insert it
Document doc = new Document("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest earlier on)
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can explore queries and cursors
List<Document> documents = new ArrayList<Document>();
for (int i = 0; i < 100; i++) {
documents.add(new Document("i", i));
}
collection.insertMany(documents);
System.out.println("total # of documents after inserting 100 small ones (should be 101) " + collection.countDocuments()); // find first
myDoc = collection.find().first();
System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out
MongoCursor<Document> cursor = collection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
} for (Document cur : collection.find()) {
System.out.println(cur.toJson());
} // now use a query to get 1 document out
myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson()); // now use a range query to get a larger subset
cursor = collection.find(gt("i", 50)).iterator(); try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
} // range query with multiple constraints
cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
} // Query Filters
myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson()); // now use a range query to get a larger subset
Consumer<Document> printBlock = new Consumer<Document>() {
@Override
public void accept(final Document document) {
System.out.println(document.toJson());
}
};
collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100
collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting
myDoc = collection.find(exists("i")).sort(descending("i")).first();
System.out.println(myDoc.toJson()); // Projection
myDoc = collection.find().projection(excludeId()).first();
System.out.println(myDoc.toJson()); // Aggregation
collection.aggregate(asList(
match(gt("i", 0)),
project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))
).forEach(printBlock); myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
System.out.println(myDoc.toJson()); // Update One
collection.updateOne(eq("i", 10), set("i", 110)); // Update Many
UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
System.out.println(updateResult.getModifiedCount()); // Delete One
collection.deleteOne(eq("i", 110)); // Delete Many
DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
System.out.println(deleteResult.getDeletedCount()); // Create Index
collection.createIndex(new Document("i", 1)); // Clean up
database.drop(); // release resources
mongoClient.close();
}
}
mongodb QuickStart Demo的更多相关文章
- nodejs中使用mongodb quickstart
nodejs中使用mongodb quickstart node 中使用mongodb的quick start.整理的官网crud简单例子. 在百度找了几篇帖子都有问题,所以直接看官网了. 连接Mon ...
- 用c#操作Mongodb(附demo)
因为需要,写了一个基于泛型的helper,这样要使用起来方便一点. 为了大家也不重复造轮子,所以发出来希望能帮到谁. 复杂的查询最好用linq,这也是mongodb官方建议的. mongodb的C#配 ...
- NodeJs + mongodb模块demo
代码比较通俗易懂,但是我还是在这个过程中浪费了不少时间,也算是看到了nodejs中异步的一个小坑.未来的坑还有很多,慢慢找坑填坑吧. 参考资料如下: 1.断言模块 : https://nodejs.o ...
- [MongoDB]对数组操作
摘要 在实际开发中遇到更新某个document中的数组的值,这里做一下记录. 这里使用的驱动为 using MongoDB.Bson;using MongoDB.Driver; 相关文章 [Mongo ...
- MongoDB,HDFS, Spark to 电影推荐
http://www.infoq.com/cn/news/2014/12/mongdb-spark-movie-recommend MovieWeb是一个电影相关的网站,它提供的功能包括搜索电影信息. ...
- debezium mongodb 集成测试
debezium 是一个方便的cdc connector 可以帮助我们解决好多数据实时变更处理.数据分析.微服务的数据通信 从上次跑简单demo到现在,这个工具是有好多的变更,添加了好多方便的功能,支 ...
- MongoDB学习之(三)增删查改
发现一篇Java操作MongoDb不错的文章,记录一下: https://www.cnblogs.com/sa-dan/p/6836055.html 基本功能. import java.util.Ar ...
- MongoDB 学习(一)安装配置和简单应用
一.安装和部署 1.服务端安装 1.官网下载(官方网站 https://www.mongodb.org/downloads/#production),傻瓜式安装,注意修改安装路径. 安装完成后的目录结 ...
- Koa 操作 Mongodb 数据库
node-mongodb-native的介绍 使用基于官方的 node-mongodb-native 驱动,封装一个更小.更快.更灵活的 DB 模块, 让我们用 nodejs 操作 Mongodb 数 ...
- mongodb与java的整合
mongodb的相关命令我们这里不在赘述,因为其文档下写的非常清楚,也很容易懂.这里我们说一下其余java的整合,mongodb配置请查看官方文档 1.首先我们应该导入期相关依赖, org.mongo ...
随机推荐
- 关于多个 Cookie 的分隔符这件事
对于 Cookie 的处理上,我最近遇到一个问题,那就是如何分割 Cookie 的内容.有人说是使用逗号分割,有人说是使用分号分割,究竟用哪个才是对的?其实这个答案是需要分为两个过程,分别是请求和响应 ...
- 2019-8-31-dotnet-使用-Environment.FailFast-结束程序
title author date CreateTime categories dotnet 使用 Environment.FailFast 结束程序 lindexi 2019-08-31 16:55 ...
- OLAP系列之分析型数据库clickhouse集群部署(二)
一.环境准备 IP 配置 clickhouse版本 zookeeper版本 myid 192.168.12.88 Centos 7.9 4核8G 22.8.20.11 3.7.1 3 192.168. ...
- OSI模型之网络层
一.简介 网络层是OSI参考模型中的第三层,同时也是TCP/IP模型的第二层.它介于传输层和数据链路层之间,主要任务是把分组从源端传到目的端,为分组交换网上的不同主机提供通信服务.网络层传输单位是数据 ...
- Zookeeper中的角色
在zookeeper集群中,节点也有不同的角色,承担着不同角色. zookeeper有三种角色: 老大:Leader (领导者) : 客户端提供读服务和写服务. 老二:Follower(跟随者 ...
- 小伙伴说VuePress太简洁了,还有没有其他博客推荐?
写在前面 自从上一篇文章发出来之后,不少小伙伴开始用VuePress搭建自己的个人网站. 如果小伙伴也想用VuePress零代码零成本搭建个人网站,可以看过来 传送门 怎么零代码零成本搭建个人网站 当 ...
- NASM中的Preprocessor
NASM中的Preprocessor都以%开头. 单行macro %define %define与C语言中的#define类似: %define a(x) 1+b(x) %define b(x) 2* ...
- wordpress多站点设置,移除 多站点链接中的 /blog 前缀
★★★最近想给自己的wordpress添加多个站点,就查了查相关的设置方法,以下我亲自尝试可行 1.首先需要开始配置:在网站根目录下的 wp-config.php 添加: define('WP_ALL ...
- 腾讯、阿里、B站最新面经汇总,有的妥妥的凉经。
除了BAT(没错我说的B是B站的B),还有网易.希音科技.美柚等中小厂的最新面经. 这次投稿的同学行文幽默风趣,处处透漏着不成功便搞笑的骚气. 祝他早日上岸,也欢迎大家在评论区讨论这些面试题,有哪些面 ...
- C语言:如何删除超链接
单独写出一个函数出来,基本思想就是用fscanf一个一个字符读取出来,(文本流只能用fscanf,不能用fgetc等用于二进制流的函数,不然会导致乱码)遇到<的时候就停止读取,先把之前存进cop ...