官方资料:
MongoDB官方安装环境 https://www.mongodb.com/download-center?jmp=nav#community
rodo3t可视化工具 https://mac.softpedia.com/get/Developer-Tools/Robomongo.shtml
懒人模式:
链接:链接: https://pan.baidu.com/s/1iAjJifUkDHXMphJu2GWNPg 提取码: zcac
MongoDB的安装版基本配置1。运行mongodb-win32-x86_64-2008plus-ssl-4.0.2-signed.msi
选择自定义安装
设置账号密码
绿色版基本配置1.1打开mongodb-win32-x86 _… mongodb的执行文件
1.2右键编辑start.bat启动脚本
注:start.bat文件中 bin\mongodb.exe 启动mongodb
-dur 数据目录 & 日志目录
--dbpath 数据目录 , 需要自己创建data目录。
--logpath 日志目录 , 需要自己创建logs目录。
--logappend 日志追加模式
完整目录创建如下:
1.3双击启动start.bat脚本
rodo3t的可视化工具1.1打开rodo3t-1.2.1 …目录,双击启动rodo3t.exe
1.2点击创建创建一个连接
1.3设置连接名,和端口。点击保存
基本数据准备完毕
MongoDB和Java简单结合使用
创建maven项目,导入mongodb所需坐标
复制代码
通过Java的代码获得连接
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
复制代码
创建文档,插入数据
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
//创建文档
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
System.out.println("集合 user 选择成功");
//准备数据
Document document = new Document("name", "gdj").
append("sex", "男").
append("age", 18).
append("phone", "17633923693");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
//将数据存入数据库
collection.insertMany(documents);
System.out.println("文档插入成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
复制代码
代码运行后结果:
注:id自动生成
查询所有
public static void main( String args[] ){
try{
ollection<Document> collection = mongoDatabase.getCollection("user");
//查询所有
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
复制代码
控制台打印结果
修改数据
//更新文档 将文档中 age=18 的文档修改为 age=20
collection.updateMany(Filters.eq("age", 18), new Document("$set",new Document("age",20)));
复制代码
控制台打印结果
数据库效果
删除数据
//删除符合条件的第一个文档
collection.deleteOne(Filters.eq("age", 18));
//删除所有符合条件的文档
collection.deleteMany (Filters.eq("age", 18));
复制代码