zoukankan      html  css  js  c++  java
  • NodeJS 操作MongoDB 数据库

    安装 MongoDB 

    npm install mongodb --save

    连接 MongoDB 数据库:

    //引入mongodb
    const {MongoClient} = require('mongodb')
    
    //定义数据库连接的地址
    //const dataUrl = 'mongodb://127.0.0.1:27017'
    //如果数据库开启了权限验证:
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    //定义要操作的数据库
    const dbName = 'hello'
    
    //实例化MongoClient,传入数据库连接地址
    const client = new MongoClient(dataUrl, { useUnifiedTopology: true })
    
    //连接数据库
    client.connect(err=>{
        if(err){
            console.log("数据库连接失败:",err)
            return
        }
        console.log("数据库连接成功")
    })

    官方示例:

    https://docs.mongodb.com/drivers/node

    const MongoClient = require('mongodb').MongoClient;
    const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
    const client = new MongoClient(uri, { useNewUrlParser: true });
    client.connect(err => {
      const collection = client.db("test").collection("devices");
      // perform actions on the collection object
      client.close();
    });
    

     也可以另一种方式连接数据库:

    const { MongoClient } = require('mongodb')
    
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    const dbName = 'hello'
    
    //连接数据库
    MongoClient.connect(dataUrl, { useUnifiedTopology: true },(err,client) => {
        if (err) {
            console.log("数据库连接失败:", err)
            return
        }
        console.log("数据库连接成功")
    
        //删除一条数据
        let db=client.db(dbName)
        db.collection('user').deleteOne({ "name": "jack20" } ,(err)=>{
            if(err){
                console.log("删除数据库中的数据失败:",err)
                return
            }
            console.log("删除数据库中的数据成功")
            client.close()
        })
    })
    

      

    NodeJS查找MongoDB数据库的数据:

    //引入mongodb
    const {MongoClient} = require('mongodb')
    
    //定义数据库连接的地址
    //const dataUrl = 'mongodb://127.0.0.1:27017'
    //如果数据库开启了权限验证:
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    //定义要操作的数据库
    const dbName = 'hello'
    
    //实例化MongoClient,传入数据库连接地址
    const client = new MongoClient(dataUrl, { useUnifiedTopology: true })
    
    //连接数据库
    client.connect(err=>{
        if(err){
            console.log("数据库连接失败:",err)
            return
        }
        console.log("数据库连接成功")
    
        //查找数据
        let db=client.db(dbName)
        db.collection('user').find({"age":13}).toArray((err,data)=>{
            if(err){
                console.log("查询失败:",err)
                return
            }
            console.log("查询数据成功:",data)
            client.close() //操作数据库完毕之后,一定要关闭数据库连接
        })
    })
    
    /**
     * [ { _id: 5eec5070b23b0bc30e70677f, ID: 8, name: 'jack8', age: 13 } ]
     */
    

    数据库中的数据:

    > db.user.find()
    { "_id" : ObjectId("5eec5070b23b0bc30e706778"), "ID" : 1, "name" : "jack1", "age" : 6 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706779"), "ID" : 2, "name" : "jack2", "age" : 7 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677a"), "ID" : 3, "name" : "jack3", "age" : 8 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677b"), "ID" : 4, "name" : "jack4", "age" : 9 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677c"), "ID" : 5, "name" : "jack5", "age" : 10 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677d"), "ID" : 6, "name" : "jack6", "age" : 11 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677e"), "ID" : 7, "name" : "jack7", "age" : 12 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677f"), "ID" : 8, "name" : "jack8", "age" : 13 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706780"), "ID" : 9, "name" : "jack9", "age" : 14 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706781"), "ID" : 10, "name" : "jack10", "age" : 15 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706782"), "ID" : 11, "name" : "jack11", "age" : 16 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706783"), "ID" : 12, "name" : "jack12", "age" : 17 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706784"), "ID" : 13, "name" : "jack13", "age" : 18 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706785"), "ID" : 14, "name" : "jack14", "age" : 19 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706786"), "ID" : 15, "name" : "jack15", "age" : 20 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706787"), "ID" : 16, "name" : "jack16", "age" : 21 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706788"), "ID" : 17, "name" : "jack17", "age" : 22 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706789"), "ID" : 18, "name" : "jack18", "age" : 23 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70678a"), "ID" : 19, "name" : "jack19", "age" : 24 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70678b"), "ID" : 20, "name" : "jack20", "age" : 25 }
    >

    增加数据到数据库中:

    //引入mongodb
    const {MongoClient} = require('mongodb')
    
    //定义数据库连接的地址
    //const dataUrl = 'mongodb://127.0.0.1:27017'
    //如果数据库开启了权限验证:
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    //定义要操作的数据库
    const dbName = 'hello'
    
    //实例化MongoClient,传入数据库连接地址
    const client = new MongoClient(dataUrl, { useUnifiedTopology: true })
    
    //连接数据库
    client.connect(err=>{
        if(err){
            console.log("数据库连接失败:",err)
            return
        }
        console.log("数据库连接成功")
    
        //增加数据
        let db=client.db(dbName)
        db.collection('user').insertOne({"name":"sally","age":33},(err,result)=>{
            if(err){
                console.log("增加数据到数据库中失败:",err)
                return
            }
            console.log("增加数据到数据库中成功:",result)
            client.close()
        })
    })
    
    /**
     *  CommandResult {
      result: { n: 1, ok: 1 },
      connection: Connection {
        _events: [Object: null prototype] {
          commandStarted: [Function],
          commandFailed: [Function],
          commandSucceeded: [Function],
          clusterTimeReceived: [Function]
        },
        _eventsCount: 4,
        _maxListeners: undefined,
        id: 1,
        address: '127.0.0.1:27017',
        bson: BSON {},
        socketTimeout: 360000,
        monitorCommands: false,
        closed: false,
        destroyed: false,
        lastIsMasterMS: 2,
        [Symbol(description)]: StreamDescription {
          address: '127.0.0.1:27017',
          type: 'Standalone',
          minWireVersion: 0,
          maxWireVersion: 8,
          maxBsonObjectSize: 16777216,
          maxMessageSizeBytes: 48000000,
          maxWriteBatchSize: 100000,
          compressors: []
        },
        [Symbol(generation)]: 0,
        [Symbol(lastUseTime)]: 21843992,
        [Symbol(queue)]: Map {},
        [Symbol(messageStream)]: MessageStream {
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 7,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: true,
          allowHalfOpen: true,
          bson: BSON {},
          maxBsonMessageSize: 67108864,
          [Symbol(buffer)]: [BufferList]
        },
        [Symbol(stream)]: Socket {
          connecting: false,
          _hadError: false,
          _parent: null,
          _host: 'localhost',
          _readableState: [ReadableState],
          readable: true,
          _events: [Object: null prototype],
          _eventsCount: 7,
          _maxListeners: undefined,
          _writableState: [WritableState],
          writable: true,
          allowHalfOpen: false,
          _sockname: null,
          _pendingData: null,
          _pendingEncoding: '',
          server: null,
          _server: null,
          timeout: 360000,
          _peername: [Object],
          [Symbol(asyncId)]: 37,
          [Symbol(kHandle)]: [TCP],
          [Symbol(lastWriteQueueSize)]: 0,
          [Symbol(timeout)]: Timeout {
            _idleTimeout: 360000,
            _idlePrev: [TimersList],
            _idleNext: [Timeout],
            _idleStart: 303,
            _onTimeout: [Function: bound ],
            _timerArgs: undefined,
            _repeat: null,
            _destroyed: false,
            [Symbol(refed)]: false,
            [Symbol(asyncId)]: 50,
            [Symbol(triggerId)]: 37
          },
          [Symbol(kBuffer)]: null,
          [Symbol(kBufferCb)]: null,
          [Symbol(kBufferGen)]: null,
          [Symbol(kBytesRead)]: 0,
          [Symbol(kBytesWritten)]: 0
        },
        [Symbol(ismaster)]: {
          ismaster: true,
          maxBsonObjectSize: 16777216,
          maxMessageSizeBytes: 48000000,
          maxWriteBatchSize: 100000,
          localTime: 2020-06-19T08:03:37.576Z,
          logicalSessionTimeoutMinutes: 30,
          connectionId: 22,
          minWireVersion: 0,
          maxWireVersion: 8,
          readOnly: false,
          ok: 1
        }
      },
      message: BinMsg {
        parsed: true,
        raw: <Buffer 2d 00 00 00 b5 02 00 00 07 00 00 00 dd 07 00 00 00 00 00 00 00 18 00 00 00 10 6e 00 01 00 00 00 01 6f 6b 00 00 00 00 00 00 00 f0 3f 00>,
        data: <Buffer 00 00 00 00 00 18 00 00 00 10 6e 00 01 00 00 00 01 6f 6b 00 00 00 00 00 00 00 f0 3f 00>,
        bson: BSON {},
        opts: { promoteLongs: true, promoteValues: true, promoteBuffers: false },
        length: 45,
        requestId: 693,
        responseTo: 7,
        opCode: 2013,
        fromCompressed: undefined,
        responseFlags: 0,
        checksumPresent: false,
        moreToCome: false,
        exhaustAllowed: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        documents: [ [Object] ],
        index: 29
      },
      ops: [ { name: 'sally', age: 33, _id: 5eec7159787dcd3754b6eaa0 } ],
      insertedCount: 1,
      insertedId: 5eec7159787dcd3754b6eaa0
    }
     */
    

    数据库查询这条记录是否添加了:

    > db.user.find().count()
    21
    > db.user.find({"name":"sally"})
    { "_id" : ObjectId("5eec7159787dcd3754b6eaa0"), "name" : "sally", "age" : 33 }
    >
    

      

    修改数据库中的数据:

    //引入mongodb
    const {MongoClient} = require('mongodb')
    
    //定义数据库连接的地址
    //const dataUrl = 'mongodb://127.0.0.1:27017'
    //如果数据库开启了权限验证:
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    //定义要操作的数据库
    const dbName = 'hello'
    
    //实例化MongoClient,传入数据库连接地址
    const client = new MongoClient(dataUrl, { useUnifiedTopology: true })
    
    //连接数据库
    client.connect(err=>{
        if(err){
            console.log("数据库连接失败:",err)
            return
        }
        console.log("数据库连接成功")
    
        //修改数据
        let db=client.db(dbName)
        db.collection('user').updateOne({ "name": "sally" }, { $set: { "age": 60 } },(err,result)=>{
            if(err){
                console.log("修改数据库中的数据失败:",err)
                return
            }
            console.log("修改数据库中的数据成功:",result)
            client.close()
        })
    })

    /**
    修改数据库中的数据成功:。。。。

    */

    数据库中再去查看这条记录是否修改了:

    > db.user.find({"name":"sally"})
    { "_id" : ObjectId("5eec7159787dcd3754b6eaa0"), "name" : "sally", "age" : 60 }
    >
    

    删除数据库中的数据:

    删除一条数据:

    //引入mongodb
    const {MongoClient} = require('mongodb')
    
    //定义数据库连接的地址
    //const dataUrl = 'mongodb://127.0.0.1:27017'
    //如果数据库开启了权限验证:
    const dataUrl = 'mongodb://admin:123@localhost:27017/'
    
    //定义要操作的数据库
    const dbName = 'hello'
    
    //实例化MongoClient,传入数据库连接地址
    const client = new MongoClient(dataUrl, { useUnifiedTopology: true })
    
    //连接数据库
    client.connect(err=>{
        if(err){
            console.log("数据库连接失败:",err)
            return
        }
        console.log("数据库连接成功")
    
        //删除一条数据
        let db=client.db(dbName)
        db.collection('user').deleteOne({ "name": "sally" } ,(err)=>{
            if(err){
                console.log("删除数据库中的数据失败:",err)
                return
            }
            console.log("删除数据库中的数据成功")
            client.close()
        })
    })
    

    去数据库中查看是否删除了:

    > db.user.find().count()
    20
    > db.user.find({"name":"sally"})
    >
    

    删除多条数据:

     去数据库中查看删除情况:

    > db.user.find().count()
    16
    > db.user.find()
    { "_id" : ObjectId("5eec5070b23b0bc30e70677c"), "ID" : 5, "name" : "jack5", "age" : 10 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677d"), "ID" : 6, "name" : "jack6", "age" : 11 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677e"), "ID" : 7, "name" : "jack7", "age" : 12 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70677f"), "ID" : 8, "name" : "jack8", "age" : 13 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706780"), "ID" : 9, "name" : "jack9", "age" : 14 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706781"), "ID" : 10, "name" : "jack10", "age" : 15 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706782"), "ID" : 11, "name" : "jack11", "age" : 16 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706783"), "ID" : 12, "name" : "jack12", "age" : 17 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706784"), "ID" : 13, "name" : "jack13", "age" : 18 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706785"), "ID" : 14, "name" : "jack14", "age" : 19 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706786"), "ID" : 15, "name" : "jack15", "age" : 20 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706787"), "ID" : 16, "name" : "jack16", "age" : 21 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706788"), "ID" : 17, "name" : "jack17", "age" : 22 }
    { "_id" : ObjectId("5eec5070b23b0bc30e706789"), "ID" : 18, "name" : "jack18", "age" : 23 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70678a"), "ID" : 19, "name" : "jack19", "age" : 24 }
    { "_id" : ObjectId("5eec5070b23b0bc30e70678b"), "ID" : 20, "name" : "jack20", "age" : 25 }
    >
    

      

  • 相关阅读:
    AS400一些有用的命令
    Publish的时候某些需要用到的文件没deploy上去
    DB2一些SQL的用法
    根据PostgreSQL 系统表查出字段描述
    linux memcached 安装
    CentOS下XEN虚拟服务器安装配置
    Apache the requested operation has failed
    PHP配置兼容ZendDebugger和Optimizer
    虚拟机比较
    memcache 运行情况,内存使用
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/13163714.html
Copyright © 2011-2022 走看看