插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容

时间:2023-03-09 07:17:18
插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert'); const url = 'mongodb://127.0.0.1:27017'; const dbName = 'jhblog';
MongoClient.connect(url, {useNewUrlParser:true}, function (err, client) {
assert.equal(null, err);
console.log('Connected successfully to server');
const db = client.db(dbName); db.collection("posts", function (err, collection) {
var list = [
{title: "马里奥", tag:"game"},
{title: "node.js", tag:"it"}
];
collection.insert(list, function (err, result) {
assert.equal(null, err);
client.close();
});
}); });

1、npm install mongodb

2、node test.js

3、mongo(进入mongo控制台)

4、show dbs(显示数据库列表 )

插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容

5、use jhblog

插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容

6、show collections(显示当前数据库中的集合(类似关系数据库中的表))

插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容

7、db.posts.find()

插入MongoDB文档:mongo控制台查看插入到MongoDB文档中的内容

8、exit 退出mongo控制台