Node使用 MongoDB

最近项目中需要使用MongoDB做数据存储,从安装到简单使用做下记录

Mac安装MongoDB

Mac上使用 brew 安装MongoDB相对比较简单

brew tap mongodb/brew
brew install mongodb-community //可以在后面跟版本号,安装指定版本brew install [email protected]

安装信息:

  • 配置文件:/usr/local/etc/mongod.conf
  • 日志文件路径:/usr/local/var/log/mongodb
  • 数据存放路径:/usr/local/var/mongodb

运行MongoDB:

我们可以使用 brew 命令或 mongod 命令来启动服务。
brew 启动:

$ brew services start mongodb-community
==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)

brew 停止:

$ brew services stop mongodb-community
Stopping `mongodb-community`... (might take a while)

brew 重启

$ 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很类似,常用的操作命令如下
命令行打开数据库

$ 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

列出所有数据库

> show dbs
admin      40.00 KiB
aysncnpm  260.00 KiB
config     84.00 KiB
local      72.00 KiB

显示当前数据库

> db
test

创建&&切换数据库

> use aysncnpm  //如果数据库不存在,则创建数据库,否则切换到指定数据库。
switched to db aysncnpm

增删查改

> db.npm.insert({name:'react1'})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("6317612fbfac6e8caca29d5a") }
}

> db.npm.find({name:'react1})  //查
[ { _id: ObjectId("6317612fbfac6e8caca29d5a"), name: 'react1' } ]

> db.npm.update({name:'react1'},{$set:{name:'resct2'}}) //更新
DeprecationWarning: Collection.update() is deprecated. Use updateOne, updateMany, or bulkWrite.
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

> db.npm.remove({name:'react2'}) //删除
{ acknowledged: true, deletedCount: 0 }

node.js链接MongoDB

使用npm安装MongoDB

npm install mongodb

创建链接

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();
});

创建集合

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();
    });
});

增删查改

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("aysncnpm");
    var myobj = { name: "react1"};
    dbo.collection("npm").insertOne(myobj, function(err, res) {
        if (err) throw err;
        console.log("文档插入成功");
        db.close();
    });
    dbo.collection("npm").find(myobj).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });
    dbo.collection("npm").updateOne(myobj, {$set:{name:'resct2'}}, function(err, res) {
        if (err) throw err;
        console.log("文档更新成功");
        db.close();
    });
    dbo.collection("npm"). deleteOne(myobj, function(err, obj) {
        if (err) throw err;
        console.log("文档删除成功");
        db.close();
    });
});

版权声明:
作者:Zad
链接:https://www.techfm.club/p/43342.html
来源:TechFM
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>