美文网首页
MongoDB---增删查改

MongoDB---增删查改

作者: Wrestle_Mania | 来源:发表于2021-04-24 17:13 被阅读0次
    • 新增(一条或多条)
    const MongoClient = require("mongodb").MongoClient;
    
    const url = "mongodb://localhost:27017";
    const dbName = "demo";
    const client = new MongoClient(url, { useUnifiedTopology: true });
    
    client.connect(err => {
      const db = client.db(dbName);
      db.collection("student").insertOne(
        { name: "Cercei", age: 22 },
        (err, result) => {
          if (err) throw err;
          console.log("数据插入成功");
          client.close();
        }
      );
    });
    
    • 查找
    const MongoClient = require("mongodb").MongoClient;
    
    const url = "mongodb://localhost:27017";
    const dbName = "demo";
    const client = new MongoClient(url, { useUnifiedTopology: true });
    
    client.connect(err => {
      const db = client.db(dbName);
      db.collection("student")
        .find({})
        .toArray((err, docs) => {
          if (err) throw err;
          console.log(docs);
          client.close();
        });
    });
    
    • 连接与查找数据库时间对比(主要时间耗费在数据库的连接上
    const MongoClient = require("mongodb").MongoClient;
    
    const url = "mongodb://localhost:27017";
    const dbName = "demo";
    const client = new MongoClient(url, { useUnifiedTopology: true });
    
    console.time("connect");
    client.connect(err => {
      console.time("find");
      const db = client.db(dbName);
      db.collection("student")
        .find({})
        .toArray((err, docs) => {
          if (err) throw err;
          console.log(docs);
          console.timeEnd("connect"); //connect: 1053.064ms
          console.timeEnd("find"); //find: 22.595ms
          client.close();
        });
    });
    

    相关文章

      网友评论

          本文标题:MongoDB---增删查改

          本文链接:https://www.haomeiwen.com/subject/yfjlrltx.html