zoukankan      html  css  js  c++  java
  • 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();
    })
  • 相关阅读:
    HDU 2594 扩展kmp模板题
    HDU 1358 简单kmp
    HDU 3336 扩展kmp
    SPOJ SUBLEX 求第k小子串
    Codeforces 235C
    HDU 4622 Reincarnation
    HDU 4622 求解区间字符串中的不同子串的个数
    [LeetCode] Length of Last Word 字符串查找
    [LeetCode] Sudoku Solver 解数独,递归,回溯
    [LeetCode] Longest Common Prefix 字符串公有前序
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/13920730.html
Copyright © 2011-2022 走看看