> show dbs
runoob 0.000GB # 自动创建了 runoob 数据库
> show tables
site # 自动创建了 site 集合(数据表)
> db.site.find()
{ "_id" : ObjectId("5a794e36763eb821b24db854"), "name" : "软件开发网", "url" : "www.runoob" }
>
如果要插入多条数据可以使用 insertMany():
插入多条数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var myobj = [
{ name: '菜鸟工具', url: 'https://c.mscto.com', type: 'cn'},
{ name: 'Google', url: 'https://www.google.com', type: 'en'},
{ name: 'Facebook', url: 'https://www.google.com', type: 'en'}
];
dbo.collection("site").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("插入的文档数量为: " + res.insertedCount);
db.close();
});
});
res.insertedCount 为插入的条数。
查询数据
可以使用 find() 来查找数据, find() 可以返回匹配条件的所有数据。
如果未指定条件,find() 返回集合中的所有数据。
find()
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection("site"). find({}).toArray(function(err, result) { // 返回集合中所有数据
if (err) throw err;
console.log(result);
db.close();
});
});
以下实例检索 name 为 “软件开发网” 的实例:
查询指定条件的数据
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
var whereStr = {"name":'软件开发网'}; // 查询条件
dbo.collection("site").find(whereStr).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
执行以下命令输出就结果为:
[ { _id: 5a794e36763eb821b24db854,
name: '软件开发网',
url: 'www.runoob' } ]
更新数据
我们也可以对数据库的数据进行修改,以下实例将 name 为 “软件开发网” 的 url 改为 https://www.mscto.com:









