const MongoClient = require('mongodb').MongoClient; const ObjectId = require('mongodb').ObjectId; const url = "mongodb://localhost:27017"; // 创建数据库与集合 MongoClient.connect(url, function(err, client) { if (err) throw err; console.log("数据库已创建!"); let dbase = client.db("rundb"); dbase.createCollection('list', function(err, res){ if (err) throw err; console.log("创建集合!"); console.log(res); client.close(); }) }); MongoClient.connect(url, function(err, client) { const col = client.db('rundb').collection('list'); if(err) throw err; // 插入 col.insert([ {a:1, b:1}, {a:2, b:2}, {a:3, b:3}, {a:4, b:4} ], function(err, res){ if(err) throw err; console.log('插入结果:'); console.log(res); }) // 增加 col.save( {name: '冯绍峰', age: 30, country: '中国'} , function(err, res){ if(err) throw err; console.log('增加结果:'); console.log(res); }) // 删除 col.remove({a: 4}, function(err, res){ if(err) throw err; console.log('删除结果:'); console.log(res); }) // 更新 col.update({"_id" : ObjectId("5fa0fa19b605a03f70c72178")},{ $set:{name: '李宗盛'} },function(err, res){ if(err) throw err; console.log('更新结果:'); console.log(res); }) // 查找 col.find().toArray(function(err, res){ if(err) throw err; console.log('查询结果:'); console.log(res); }) client.close(); })