1、安裝MongoDB
npm install mongodb --save-dev? /? cnpm install mongodb --save-dev
2、要在 MongoDB 中創(chuàng)建一個(gè)數(shù)據(jù)庫,首先我們需要?jiǎng)?chuàng)建一個(gè) MongoClient 對(duì)象,然后配置好指定的 URL 和 端口號(hào)。
如果數(shù)據(jù)庫不存在,MongoDB 將創(chuàng)建數(shù)據(jù)庫并建立連接。
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/runoob";
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {??
if (err) throw err;
? console.log("數(shù)據(jù)庫已創(chuàng)建!");
? db.close();
});
3、創(chuàng)建數(shù)據(jù)庫student
var student = db.db('student')
4、數(shù)據(jù)庫student中創(chuàng)建表user
student.createCollection('user',function(err,res){})
5、user表中插入一條數(shù)據(jù)myobj
student.collection('user').insertOne(myobj,function(err,res){})
user表中插入多條數(shù)據(jù)myobj
student.collection('user').insertMany(myobj,function(err,res){})
6、查找
student.collection("user"). find({}).toArray(function(err, result) { // 返回集合中所有數(shù)據(jù) if (err) throw err;
? ? ? ? console.log(result);
? ? ? ? db.close();
? ? });
7、更新一條
var whereStr = {"name":'菜鳥教程'}; // 查詢條件?
?var updateStr = {$set: { "url" : "https://www.runoob.com" }};
?student.collection("user").updateOne(whereStr, updateStr, function(err, res) {? ? ?
?? if (err) throw err;
? ? ? ? console.log("文檔更新成功");
? ? ? ? db.close();
? ? });
更新多條數(shù)據(jù)使用updateMany()
8、刪除一條張三的數(shù)據(jù)
var whereStr = {'name':'張三'}
student.collection('user').deleteOne(whereStr,function(err,res){})
刪除多條數(shù)據(jù)deleteMany()
9、排序sort()
參數(shù){ type: 1 } // 按 type 字段升序
{ type: -1 } // 按 type 字段降序
使用
student.collect('user').find().sort({'name':1}).toArray(function(err,result){})
10、查詢分頁limit()
如果要設(shè)置指定的返回條數(shù)可以使用?limit()?方法,該方法只接受一個(gè)參數(shù),指定了返回的條數(shù)。
student.collect('user').find().limit(number).toArray(function(err,result){})
11、跳過指定數(shù)據(jù)
如果要指定跳過的條數(shù),可以使用?skip()?方法。
跳過前面兩條數(shù)據(jù),讀取兩條數(shù)據(jù)
student.collect('user').find().skip(2).limit(2).toArray(function(err,result){})
12、刪除集合drop()
student.collection("user").drop(function(err, delOK) { // 執(zhí)行成功 delOK 返回 true,否則返回 false?
?if (err) throw err;
? ? ? ? if (delOK) console.log("集合已刪除");
? ? ? ? db.close();
? ? });