Node操作Mongodb
1.Node连接数据库
// 导入mongodb中的链接对象const MongoClient = require('mongodb').MongoClient;// 数据库服务器地址const url = 'mongodb://localhost:27017';// 数据库的名字const dbName = 'test';// 连接数据库服务器MongoClient.connect(url, function(err, client) { //连接数据库 const adminDb = client.db(dbName); // 关闭数据库的连接 client.close(); });});
2. 查询数据库中的内容
// 导入mongodb中的链接对象const MongoClient = require('mongodb').MongoClient// 数据库服务器地址const url = 'mongodb://localhost:27017';// 数据库的名字const dbName = 'test';// 连接数据库服务器MongoClient.connect(url, function(err, client) { //连接数据库以及数据库中的数据集合 const col = client.db(dbName).collection("student"); // 查询数据 col.find({}).toArray(function(err,result){ // 数据库查询错误 if(err) throw err; // 查询成功返回的数据 console.log(result) /* [ { _id: 5eb50d7aec15f35088a31ac6, username: 'aa', age: 18 }, { _id: 5eb50d7aec15f35088a31ac7, username: 'bb', age: 30 }, { _id: 5eb50d7aec15f35088a31ac8, username: 'cc', age: 22 } ] */ }) // 关闭数据库的连接 client.close();});
3. 向数据库中插入内容
// 导入mongodb中的链接对象const MongoClient = require('mongodb').MongoClient// 数据库服务器地址const url = 'mongodb://localhost:27017';// 数据库的名字const dbName = 'test';// 连接数据库服务器MongoClient.connect(url, function(err, client) { //连接数据库以及数据库中的数据集合 const col = client.db(dbName).collection("student"); // 像数据库中插入数据 col.insert([ { username:"aa", age:18 }, { username:"bb", age:20 }, { username:"cc", age:20 } ], function(err, result){ // 如果数据插入错误则抛出错误 if(err) throw err // result 数据插入成功后返回的内容 console.log(result) /* { result: { ok: 1, n: 3 }, ops: [ [Object], [Object], [Object] ], insertedCount: 3, // 插入几条数据 insertedIds: { // 数据的id '0': 5eb50d7aec15f35088a31ac6, '1': 5eb50d7aec15f35088a31ac7, '2': 5eb50d7aec15f35088a31ac8 } } */ }) // 关闭数据库的连接 client.close();});
4. 更新数据
// 导入mongodb中的链接对象const MongoClient = require('mongodb').MongoClient// 数据库服务器地址const url = 'mongodb://localhost:27017';// 数据库的名字const dbName = 'test';// 连接数据库服务器MongoClient.connect(url, function(err, client) { //连接数据库以及数据库中的数据集合 const col = client.db(dbName).collection("student"); // 更新数据 student.update({ age:22 },{$set:{sex:"女"}},{multi:true}, function(err,results){ // 如果数据更新错误则抛出错误 if(err) throw err // 更新数据库成功后返回的内容 console.log(results) /* { result: { n: 2, nModified: 2, ok: 1 }, } */ })})// 关闭数据库的连接client.close();});
5. 删除数据
// 导入mongodb中的链接对象const MongoClient = require('mongodb').MongoClient// 数据库服务器地址const url = 'mongodb://localhost:27017';// 数据库的名字const dbName = 'test';// 连接数据库服务器MongoClient.connect(url, function(err, client) { //连接数据库以及数据库中的数据集合 const col = client.db(dbName).collection("student"); // 删除数据 col.deleteOne({ age: 30 }, function(err,results){ // 如果数据删除错误则抛出错误 if(err) throw err // 删除数据库成功后返回的内容 console.log(results) /* { result: { n: 1, ok: 1 },, } */ }) })})// 关闭数据库的连接client.close();});