MongoDB简单的增删改查

首先引入mongoDB的jar包

<dependencies>

   <dependency>

     <groupId>org.mongodb</groupId>

    <artifactId>mongo-java-driver</artifactId>

    <version>3.0.4</version>

  </dependency>

</dependencies>

连接数据库:
MongoClient mongoClient = new MongoClient("localhost", 27017);

两个参数都可以不填,默认是localhost合27017

获取数据表

MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

获取集合

MongoCollection<Document> collection = MongoDBUtil.getConnect().getCollection("user");

这几个方法可以进行封装方便使用

查询:

Bson filter = Filters.eq("name", "张三");
//指定查询过滤器查询
FindIterable findIterable = collection.find(filter);
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}

添加

Document document = new Document("name","张三")
.append("sex", "男")
.append("age", 18);
//插入一个文档
collection.insertOne(document);

修改

Bson filter = Filters.eq("name", "张三");
//指定修改的更新文档
Document document = new Document("$set", new Document("age", 100));
//修改单个文档
collection.updateOne(filter, document);

注意,在新版mongoDB中,也许是更新策略变化,updateOne改用replaceOne使用

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

1.WebSocket编程—Hello World

1.引入jar包<dependencies<!servlet<dependency<groupIdjavax.servlet</groupId<artifactIdjavax.servletapi</artifactId<ve