1、引入mongodb模块,并创建客户端
var mongoClient = require('mongodb').MongoClient;
2.定义url
var url = 'mongodb://127.0.0.1:27017';
3.连接数据的名称
var dbName = 'student';
4.连接数据库
mongoClient.connect(url,function (err,client) {
if (err) throw err;
console.log('连接成功');
// 连接到具体的数据库
var db = client.db(dbName);
// 获取集合
var collection = db.collection('stu');
//查询所有的
collection.find({age:{$lt:20}}).toArray(function (err,doc) {
console.log(doc);
client.close();
}):
//查询一个
collection.findOne({age:{$lt:20}},function (err,doc) {
console.log(doc);
client.close();
});
// 查找并且更新
// findAndModify (查询,排序,doc,选项,回调)
collection.findAndModify({name:'hah'},{age:1},{age:30},function (err,result) {
if (err) throw err;
console.log(result);
})
// 添加
collection.insertOne({name:'我是添加的',age:17},function (err,result) {
if (err) throw err;
console.log('插入成功');
})
// 添加多个
var arr = [
{name:'我是添加的',age:17},
{name:'隔壁老王',age:16,sex:'mail'}
];
collection.insertMany(arr,function (err,result) {
if (err) throw err;
console.log('插入成功');
client.close();
})
// 删除
collection.deleteOne({name:'隔壁老王'},function (err,result) {
if (err) throw err;
console.log('删除成功');
})
});