• MongoDB CRUD基本代码


    const MongoClient = require('mongodb').MongoClient;
    const ObjectId = require('mongodb').ObjectId;
    const url = "mongodb://localhost:27017";
    
    // 创建数据库与集合
    MongoClient.connect(url, function(err, client) {
        if (err) throw err;
        console.log("数据库已创建!");
        let dbase = client.db("rundb");
        dbase.createCollection('list', function(err, res){
            if (err) throw err;
            console.log("创建集合!");
            console.log(res);
            client.close();
        })
    });
    
    MongoClient.connect(url, function(err, client) {
        const col = client.db('rundb').collection('list');
        if(err) throw err;
        // 插入
        col.insert([
            {a:1, b:1},
            {a:2, b:2},
            {a:3, b:3},
            {a:4, b:4}
        ], function(err, res){
            if(err) throw err;
            console.log('插入结果:');
            console.log(res);
        })
    
        // 增加
        col.save(
            {name: '冯绍峰', age: 30, country: '中国'}
        , function(err, res){
            if(err) throw err;
            console.log('增加结果:');
            console.log(res);
        })
    
        // 删除
        col.remove({a: 4}, function(err, res){
            if(err) throw err;
            console.log('删除结果:');
            console.log(res);
        })
    
        // 更新
        col.update({"_id" : ObjectId("5fa0fa19b605a03f70c72178")},{
            $set:{name: '李宗盛'}
        },function(err, res){
            if(err) throw err;
            console.log('更新结果:');
            console.log(res);
        })
    
        // 查找
        col.find().toArray(function(err, res){
            if(err) throw err;
            console.log('查询结果:');
            console.log(res);
        })
    
        client.close();
    })
  • 相关阅读:
    Kvm --01 虚拟化基础概念
    Git--09 创建Maven项目
    Git--08 Jenkins
    Git--07 Gitlab备份与恢复
    Git --06 Git-gui安装
    Git --05 Gitlab使用
    Git--04 Github使用
    socket 释放全过程
    动态规划习题总结
    linux heap堆分配
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13920730.html
Copyright © 2020-2023  润新知