$ brew services stop mongodb-community Stopping `mongodb-community`... (might take a while)
brew 重启
1 2 3 4
$ brew services restart mongodb-community Stopping `mongodb-community`... (might take a while) ==> Successfully stopped `mongodb-community` (label: homebrew.mxcl.mongodb-community) ==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)
数据库操作
MongoDB的语法和MySql很类似,常用的操作命令如下 命令行打开数据库
1 2 3 4 5
$ mongosh Current Mongosh Log ID: 63175e14bfac6e8caca29d59 Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.4 Using MongoDB: 6.0.1 Using Mongosh: 1.5.4
列出所有数据库
1 2 3 4 5
> show dbs admin 40.00 KiB aysncnpm 260.00 KiB config 84.00 KiB local 72.00 KiB
显示当前数据库
1 2
> db test
创建&&切换数据库
1 2
> use aysncnpm //如果数据库不存在,则创建数据库,否则切换到指定数据库。 switched to db aysncnpm
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/aysncnpm"; MongoClient.connect(url, function(err, db) { if (err) throw err; console.log("数据库已创建!"); db.close(); });
创建集合
1 2 3 4 5 6 7 8 9 10 11 12
var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017'; MongoClient.connect(url, function (err, db) { if (err) throw err; console.log('数据库已创建'); var dbase = db.db("aysncnpm"); dbase.createCollection('npm', function (err, res) { if (err) throw err; console.log("创建集合!"); db.close(); }); });