官网地址https://www.mongodb.com/

  • mongo的安装

  1. 点击下载https://www.mongodb.com/download-center/community
  2. 点击exe程序一步一步向下安装直到结束
  3. 配置path环境,找到C:\Program Files\MongoDB\Server\3.4\bin这个目录。电脑属性==》高级==》环境变量==》编辑path==》添加刚刚这个目录到path
  4. 打开cmd,输入mongo,出现以下这些就说明配置成功了

mongodb数据库入门

 

 

  • 数据库的连接与使用

  1. 新建mongo文件夹,复制目录
  2. 开启服务,打开cmd,输入mongod --dbpath F:\2019\node\mongo(你的路径名字)mongodb数据库入门
  3. 管理数据库(ps:另开一个cmd,刚刚那个也不要关),输入mongo  

        mongodb数据库入门

 

 

  • 数据库的增删改查

  1. 查看所有数据库show dbs
    > show dbs
    admin  0.000GB
    local  0.000GB

     

  2. 清屏cls
  3. 使用并创建数据库 use <数据库名字>(ps:use就代表了已经创建这个数据库了)
    > use school
    switched to db school

     

  4. 插入数据  db.<集合名字>.insert({"name":"希望小学1"})   (ps:集合名字自己命名,插入数据之后就会自动创建集合)

    > db.class.insert({"name":"3年级"},{"name":"4年级"})
    WriteResult({ "nInserted" : 1 })

     

  5. 显示集合名字 show collections

    > show collections
    class
    student

     

  6. 查找所有数据  db.<集合名字>.find()

    > db.student.find()
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }

     

  7. 按条件查询,举个例子,查询年龄等于12的学生

    > db.student.find({age:"12"})
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

    举个例子,查询年龄大于22的学生

    > db.student.find({age:{$gt:"22"}})
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
    { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }

    举个例子,查询年龄小于22的学生

    > db.student.find({age:{$lt:"22"}})
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

    举个例子,查询年龄小于等于12的学生

    > db.student.find({age:{$lte:"12"}})
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

    举个例子,查询年龄大于12小于52的学生

    > db.student.find({age:{$lt:"52",$gt:"12"}})
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }

    举个例子,查询名字中有wangwu的学生

    > db.student.find({name:/wangwu/})
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }

    举个例子,查询名字中以小开头的学生

    > db.student.find({name:/^小/})
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }

    举个例子,查询指定列 name的数据

    > db.student.find({},{name:1})            
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566" }
    { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby" }
    { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "name" : "小刚" }

    举个例子,查询按照年龄排序,升序1,降序-1

    > db.student.find().sort({age:1})
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }

    举个例子,查询前3条数据

    > db.student.find().limit(3)
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

    举个例子,查询后3条以后的数据

    > db.student.find().skip(3)
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
    { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }
    { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "性别" : "男", "name" : "小刚" }

    举个例子,查询2-5之间的数据

    > db.student.find().limit(3).skip(2)
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
    { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" }
    { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }

    举个例子,查询年龄为1或者年龄为12的数据

    > db.student.find({$or:[{age:"1"},{age:"12"}]})
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

    举个例子,查找第一条数据

    > db.student.findOne()
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }

    举个例子,查询某个结果的条数

    > db.student.find().count()
    7

     

  8. 修改数据,举个例子,修改名字叫小红的,改成15岁

    > db.student.update({"name":"小红"},{$set:{"age":"15"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

    如果想要完整替换,就不要出现关键字$set

    > db.student.update({"name":"小红"},{"age":"15"})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.student.find()                              })
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "age" : "15" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }

     

  9. 删除数据db.collectionsNames.remove( {} )

    > db.student.remove({"age":"32"})
    WriteResult({ "nRemoved" : 2 })
    > db.student.find()
    { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "age" : "15" }
    { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
    { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
    { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }
    { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "性别" : "男", "name" : "小刚" }

    删除表db.collectionsNames.drop()

    > show collections
    class
    student
    > db.class.drop()
    true
    > db.class.drop()
    false
    > show collections
    student
    >

    删除数据库db.dropDatabase();

 

 

 

  • MongoDB 索引 

索引是对数据库表中一列或多列的值进行排序的一种结构,可以让我们查询数据库变得更快。数字 1 表示 username 键的索引按升序存储,-1 表示 age 键的索引按照降序方式存储

  1. 创建索引:
    > db.student.ensureIndex({"name":1})
    {
            "createdCollectionAutomatically" : false,
            "numIndexesBefore" : 2,
            "numIndexesAfter" : 2,
            "note" : "all indexes already exist",
            "ok" : 1
    }

     

  2. 获取当前集合的索引
    > db.student.getIndexes()
    [
            {
                    "v" : 2,
                    "key" : {
                            "_id" : 1
                    },
                    "name" : "_id_",
                    "ns" : "school.student"
            },
            {
                    "v" : 2,
                    "key" : {
                            "name" : 1
                    },
                    "name" : "name_1",
                    "ns" : "school.student"
            },
            {
                    "v" : 2,
                    "key" : {
                            "age" : 1
                    },
                    "name" : "age_1",
                    "ns" : "school.student"
            }
    ]

     

  3. 删除索引
    > db.user.dropIndex({"name":1})
    {
            "ok" : 0,
            "errmsg" : "ns not found",
            "code" : 26,
            "codeName" : "NamespaceNotFound"
    }

     

  4. 创建唯一索引,如果name添加相同数据的话会添加不上去

    > db.student.ensureIndex({"name":1},{"unique":true})
    {
            "ok" : 0,
            "errmsg" : "Index with name: name_1 already exists with different options",
            "code" : 85,
            "codeName" : "IndexOptionsConflict"
    }

     

  • 使用nodejs操作数据库

     文档地址参考:http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/

  1. npm install mangodb --save-dev
  2. nodejs连接数据库
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017'; 
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
        });
    })
    
    app.listen(8020)

    控制台输入node app.js,刷新页面http://localhost:8020/出现数据库连接成功就代表连上数据库了

  3. 插入数据
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017';
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
    
    
            insertDocuments(db, function() {
                client.close();
            })
    
    
        });
    })
    
    app.listen(8020)
    
    //插入数据
    const insertDocuments = function(db, callback) {
        // Get the documents collection
        const collection = db.collection('student');
        // Insert some documents
        collection.insertMany([
            { name: "静静" }, { name: "忽略了" }, { name: "baby" }
        ], function(err, result) {
            assert.equal(err, null);
            assert.equal(3, result.result.n);
            assert.equal(3, result.ops.length);
            console.log("Inserted 3 documents into the collection");
            callback(result);
        });
    }

     

  4. 显示数据
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017';
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
            findDocuments(db, function() {
                client.close();
            })
    
        });
    })
    
    app.listen(8020)
    
    const findDocuments = function(db, callback) {
        // Get the documents collection
        const collection = db.collection('student');
        // Find some documents
        collection.find().toArray(function(err, docs) {
            assert.equal(err, null);
            console.log("Found the following records");
            console.log(docs)
            callback(docs);
        });
    }
  5. 改变数据

    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017';
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
            updateDocument(db, function() {
                client.close();
            })
    
        });
    })
    
    app.listen(8020)
    
    const updateDocument = function(db, callback) {
        // Get the documents collection
        const collection = db.collection('student');
        // Update document where a is 2, set b equal to 1
        collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) {
            assert.equal(err, null);
            assert.equal(1, result.result.n);
            console.log("Updated the document with the field a equal to 2");
            callback(result);
        });
    }

     

  6. 删除数据

    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017';
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
            removeDocument(db, function() {
                client.close();
            })
    
        });
    })
    
    app.listen(8020)
    const removeDocument = function(db, callback) {
        // Get the documents collection
        const collection = db.collection('student');
        // Delete document where a is 3
        collection.deleteOne({ a: 3 }, function(err, result) {
            assert.equal(err, null);
            assert.equal(1, result.result.n);
            console.log("Removed the document with the field a equal to 3");
            callback(result);
        });
    }

     

  7. 添加索引

    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    const express = require("express");
    const app = express()
    const url = 'mongodb://localhost:27017';
    
    // Database Name
    const dbName = 'school';
    
    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });
    
    app.get('/', function(req, res) {
        // Use connect method to connect to the Server
        client.connect(function(err) {
    
            res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" });
            if (err) {
                res.send("数据库连接失败");
                return;
            }
            assert.equal(null, err);
            res.write("恭喜,数据库已经成功连接 \n");
            console.log("Connected successfully to server");
    
            const db = client.db(dbName);
    
            indexCollection(db, function() {
                client.close();
            })
    
        });
    })
    
    app.listen(8020)
    
    const indexCollection = function(db, callback) {
        db.collection('student').createIndex({ "a": 1 },
            null,
            function(err, results) {
                console.log(results);
                callback();
            }
        );
    };

     

 

 

 

 

 

 

 

 

 

 

相关文章: