命令行进入mongo数据库
mongo

查看所有数据库
show dbs

新建(或已有)fruit数据表并新增数据
db.fruits.save({name: 'apple', price: 5});

查找
db.fruits.find({price: 5})

查看该数据库所有的表
db.getCollectionNames()

连接mongo数据库操作

conf.js
module.exports = {
    url: 'mongodb://127.0.0.1:27017',
    dbName: 'local',
}
db.js
const conf = require('./conf');
const { EventEmitter } = require('events');   // 数据库异步连接工具

// 客户端
const { MongoClient } = require('mongodb');
class Mongodb {
    constructor(conf) {
        this.conf = conf;
        this.emmiter = new EventEmitter();
        // 连接
        this.client = new MongoClient(conf.url, {
            useNewUrlParser: true,
        })

        this.client.connect(err => {
            console.log(err);
            if (err) {
                throw err;
            }
            console.log('连接正常');
            this.emmiter.emit('connect')
        })
    }
    col(colName, dbName = conf.dbName) {
        return this.client.db(dbName).collection(colName);
    }

    once(event, cb) {
        this.emmiter.once(event, cb)
    }
}
module.exports = new Mongodb(conf)
initData.js
const mongodb = require('./models/db');
mongodb.once('connect', async () => {
    const col = mongodb.col('fruits');
    // 删除已存在的数据
    await col.deleteMany();
    const data = new Array(100).fill().map((value, index) => {
        return {
            name: 'XXXX' + index,
            price: index,
            category: Math.random() > 0.5 ? '蔬菜' : '水果',
        }
    })
   
    await col.insertMany(data);
    console.log('插入测试数据成功');
    
})

api使用

(async () => {
    const {MongoClient: MongoDB} = require('mongodb');
   
    // 创建客户端
    const client = new MongoDB(
        'mongodb://localhost:27017', 
        {
            useNewUrlParser: true,
        }
    )
   
    let ret;
    // 创建连接
    ret = await client.connect();
    console.log('connect: ', ret);
   
    const db = client.db('local');
    const fruits = db.collection('fruits')
    
    // 删除
    ret = await fruits.deleteMany();
    
    // 添加文档
    ret = await fruits.insertOne({
        name: 'mango',
        price: 20.1
    })
    console.log('插入成功', ret.ops)
   
    // 查询
    ret = await fruits.findOne({
        name: 'mango'
    })
    console.log('查询', ret)

    // 更新
    ret = await fruits.updateOne({
        name: 'mango'
    }, {
        $set: {
            name: 'apple'
        }
    })
    console.log('更新', JSON.stringify(ret))
})()

izengx
105 声望2 粉丝

有失去的 该进阶的