java导出mongodb数据类型_04 使用java访问mongodb存取基本数据

在熟悉了命令行操作mongodb以后,这一节我们将阐述java代码如何访问mongodb。

在启动mongodb服务成功之后,这一节我们将使用命令行操作mongodb。

1、前提约束

2、操作步骤

org.springframework.boot

spring‐boot‐starter‐data‐mongodb

org.mongodb

mongo‐java‐driver

3.4.3

在项目名称/src/main/java文件夹下创建MongoDbTest.java

import com.mongodb.MongoClient;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import org.bson.Document;

public class TestMongo {

public static void main(String[] args) {

//创建mongodb 客户端

MongoClient mongoClient = new MongoClient("localhost", 27017);

//连接database

MongoDatabase database = mongoClient.getDatabase("wanho");

//创建一个collection

if (database.getCollection("student") == null) {

database.createCollection("student");

}

//连接collection

MongoCollection collection = database.getCollection("student");

//新增一条记录

Document document = new Document();

document.put("name","ali");

document.put("age","34");

collection.insertOne(document);

printAll(collection);

//更新记录

Document updateDocument = new Document();

updateDocument.append("$set", new Document().append("age", "10"));

Document searchQuery = new Document().append("name", "ali");

//更新一条记录

collection.updateOne(searchQuery, updateDocument);

printAll(collection);

//更新所有满足条件的记录

collection.updateMany(searchQuery, updateDocument);

printAll(collection);

//再次新增一条记录

Document document2 = new Document();

document2.put("name", "xiaoli");

document2.put("age", "12");

collection.insertOne(document2);

printAll(collection);

collection.deleteOne(document2);

printAll(collection);

mongoClient.close();

}

public static void printAll(MongoCollection collection) {

FindIterable findIterable = collection.find();

MongoCursor iterator = findIterable.iterator();

while (iterator.hasNext()) {

Document document = iterator.next();

System.out.println(document.toJson());

}

}

}

以上就是java代码访问操作mongodb的过程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值