mongodb从下载到编写第一个demo

注意:mongodb基于集合存储数据,对数据增删改查要先创建文档document文档对象

1、在官网下载mongodb的MSI版本

2、一直下一步,自定义路径时 注意 data数据库路径后面要加上\db\,不然无法启动mongodb服务器。

3、安装完成后,cmd进入mongodb的bin路径,查看是否安装成功

cd C:\11111111NewSoftware\MongoDB\server\4.0.10\bin

mongo

4、配置path环境变量,可以任何路径使用mongodb命令。

5、java连接mongodb

配置依赖

<dependency>

       <groupId>org.mongodb</groupId>

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

       <version>3.0.4</version>

</dependency>

6、连接mongodb

----不带认证的连接(ip和端口号可以不写,默认为localhost和27017)游客也是超级管理员的身份

MongoClient mongoClient = new MongoCLient("ip",port);

----带认证的连接--推荐

//用户名、密码、ip、端口号、数据库

String sURI = String.format("mongodb://%s:%s@%s:%d/%s", "zsmdb", "mongodb_root", "localhost", 27017, "admin");
MongoClient mongoClient = new MongoClient(new MongoClientURI(sURI));

----另外一种认证连接

List<ServerAddress> adds = new ArrayList<>();

ServerAddress serverAddress = new ServerAddress("localhost",27017);

adds.add(serverAddress); List<MongoCredential> credentials = new ArrayList<>(); //用户名、数据库名、密码 MongoCredential credential = MongoCredential.createCredential("username","database","password".toCharArray());

credentials.add(credential);

MongoClient mongoClient = new MongoClient(adds,credentials);

7、连接数据库----连接test数据库(数据库要已存在,之前没存在报错了)

MongoDatabase mongoDatabase = mongoClient.getDatabse("test")

8、创建集合collection用来存放数据,相当于table,没有则在第一次插入文档时自动创建

MongoCollection<Document> collection = mongoDatabase.getCollection("test_collect");

9、创建文档对象并插入数据

Document document = new Document();
document.append("name","zsm");
//collection.insertOne(document);//插入一条数据
Document document2 = new Document();
document2.append("name","zsm");
ArrayList list = new ArrayList<>();
list.add(document);
list.add(document2);
collection.insertMany(list);

10、查询数据

FindIterable findIterable = collection.find();//查询所有文档对象
System.out.println("++++++"+findIterable.first());
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
    System.out.println("-------"+mongoCursor.next());
}

redis相同key值会覆盖、mongodb不会

总结mongodb步骤:导入依赖--认证连接mongodb服务--连接数据库--创建集合collection--创建文档document并append数据--文档对象插入到集合中。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值