07-连接MongoDB

nobility 发布于 2022-12-09 1142 次阅读


连接MongoDB

Java连接MongoDB

需要引入相关jar包,需要引入相关jar包,从maven官网中查找mongo-java-driver并下载,导入项目即可

驱动内部就自动实现了连接池,而且是线程安全的,关闭连接就会存入连接池,下次取一样的连接时就会返回连接池中的连接,可批量创建连接与服务端对比连接数量,服务端使用db.serverStatus().connections查看连接信息

创建连接

MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);	//创建服务地址对象
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017); //创建服务地址对象
MongoClient mongoClient = new MongoClient(serverAddress);  //根据地址连接对象,创建连接对象
MongoClientOptions build = new MongoClientOptions.Builder().  //构建配置对象
    connectionsPerHost(10). //每个地址对象的最大连接数
    connectTimeout(10000).  //连接超时时间
    socketTimeout(1000).  //读写操作超时时间
    build();  //构建完毕
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017); //创建服务地址对象
MongoClient mongoClient = new MongoClient(serverAddress,build);  //根据服务地址和连接配置对象创建连对象
MongoClientURI connectionString = new MongoClientURI("mongodb://127.0.0.1:27017");	//创建连接URI
MongoClient mongoClient = new MongoClient(connectionString);	//根据URI创建连接对象

数据库操作

MongoDatabase test = mongoClient.getDatabase("test");	//使用连接对象获取数据库对象
test.createCollection("c");	//创建集合,若集合存在会报异常
MongoCollection<Document> c = test.getCollection("c");	//获取集合,若集合不存在不会报异常

集合操作

文档对象
Document document = new Document("_id",new ObjectId("5f92bed8fe37421d91ca9673")). //主键是ObjectId对象
    append("key","value").  //链式调用添加文档中的key和value
    append("array",Arrays.asList(new int[]{1}));  //若值为数组则使用List集合,也可以嵌套文档
具体操作

每个操作都有对应的API,将文档对象可做为参数,只有查询方法需要获取游标对象,再进行遍历

MongoDatabase test = mongoClient.getDatabase("test");	//使用连接对象获取数据库对象
MongoCollection<Document> c = test.getCollection("c");	//获取集合
MongoCursor<Document> iterator = c.find().iterator(); //获取游标,若是聚合操作调用aggregate()方法
while (iterator.hasNext()){ //遍历游标
  System.out.println(iterator.next());
}

Node连接MongoDB

使用npm install mongoose --save在项目中安装mongoose,mongoose是对MongoDB驱动的进一步封装,最重要的是使用模式来约束数据

const mongoose = require("mongoose"); //导入mongoose模块
const db = mongoose.createConnection("mongodb://127.0.0.1:27017", {
    dbName: "test", //连接的数据库
    poolSize: 5, //连接池大小,默认5
    connectTimeoutMS: 1000, //连接超时时间
    socketTimeoutMS: 0, //操作超时时间,默认0,无超时时间
    keepAlive: true, //是否开启长连接
    autoIndex: false, //是否自动建立索引
    useNewUrlParser: true, //是否使用新URL解析器,默认false
    useUnifiedTopology: true, //是否使用统一拓扑,默认false
    user: "root", //用户名
    pass: "root" //密码
}, err => {
    if (err) throw err
})

const model = db.model(null, //定义数据模型名
    {
        name: {
            type: String,
            default: null
        }
    }, //模式对象,若传入参数不是字符串会自动转化,可设定未传入时的默认值
    "names"); //映射的集合名

new model({}).save();   //新增文档的简单方式

model.insertMany([{}]).then(res => {    //使用Promise进行增删改查操作
    console.log(res)
    return res;
}).catch((err) => {
    throw err
}).finally(() => {
    console.log("连接关闭");    //非关系型数据库一般不会关闭连接
    db.close();
})
此作者没有提供个人介绍
最后更新于 2022-12-09