zoukankan      html  css  js  c++  java
  • mongoDB 简单使用

    mongodb传送门:

    # 第三方学习地址:
    http://blog.csdn.net/foruok/article/details/47746057
    
    # 下载mongoDB
    https://www.mongodb.com/download-center

     下载后默认是在:C:Program FilesMongoDBServer3.2in

    进入bin目录,使用以下命令开启数据库服务(需要先创建E:MongoDB_Path)

    $ ./mongod --dbpath "E:MongoDB_Path"

    此时界面会停在2015-03-26T15:19:17.135+0800 I NETWORK  [initandlisten] waiting for connections on port 27017 (此时数据库就已经启动) 

    nodejs mongodb库传送门:

    # nodejs mongodb库 github 与 官网
    https://github.com/mongodb/node-mongodb-native
    http://mongodb.github.io/node-mongodb-native/
    
    # nodejs mongoose库 github 
    https://github.com/Automattic/mongoose
    http://mongoosejs.com

    安装mongoose : npm install mongodb

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    let server = new mongo.Server(host,port,{auto_reconnect:true});
    let db = new mongo.Db('node-mongo-examples',server,{safe:true});
    
    db.open(function(err,db){
        if(err) console.log("err");
        else {
            console.log("成功建立数据库链接");
            db.close();
        }
    
        db.on('close',function(err,db){
            if(err) console.log("关闭数据库失败");
            else  console.log("关闭数据库成功");
        })
    })

     数据插入

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    
    var db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,data){
        db.collection('users',function(err,collection){
            collection.insert({
                username:"李钊鸿",
                nickname:"贝尔塔猫"
            },function(err,docs){
                console.log(docs);
                db.close();
            })
        })
    })

     查询数据

    let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,db){
        db.collection('users',function(err,collection){
            if(err) throw err;
            else {
                collection.find({}).toArray(function(err, docs){
                    console.log(docs);
                    db.close();
                })
            }
        })
    })

    /* 指定查询的字段和值 */
    {username:"李钊鸿"}

    /* 指定查询的字段并限定字段值的范围 */
    {username:{$in:['Lee','李钊鸿']}}

    /* 指定查询字段,0为忽略,1为包含 默认_id是包含的 */
    {username:"李钊鸿"},{fields:{username:1,_id:0}}

     插入多个值,同时指定多个字段的查询条件

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    var docs = [
                {type:"food",price:11},
                {type:"food",price:10},
                {type:"food",price:9},
                {type:"food",price:8},
                {type:"book",price:7}
               ];
    
    /* 多字段查询 */ let db
    = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true}); db.open(function(err,db){ db.collection('goods',function(err,collection){ collection.insert(docs,function(err, docs){ if(err) throw err; else { collection.find({type:"food",price:{$lt:10}}).toArray(function(err,docs){ if(err) throw err; else { console.log(docs); db.close(); } }) } }) }) }) /* 或查询 */ let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true}); db.open(function(err,db) { db.collection('goods',function(err,collection){ collection.find({$or:[{type:"food"},{price:{$lt:10}}]}).toArray(function(err,docs){ if(err) throw err; else { console.log(docs); db.close(); } }) }) }) /* 且与或联合查询 */ db.open(function(err,db) { db.collection('goods',function(err,collection){ collection.find({type:"food",$or:[{price:11},{price:{$lt:9}}]}).toArray(function(err,docs){ if(err) throw err; else { console.log(docs); db.close(); } }) }) })

     在查询条件中指定一个数组的完整内容

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    let article1 = {name:"TV",tags:['device','electric equipment']};
    let article2 = {name:"apple",tags:['fruit','food','citrus']};
    let article3 = {name:"Node.js",tags:['language','web','computer']};
    var docs = [article1,article2,article3];
    
    var db = new mongo.Db('node-mogo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,data){
        db.collection('articles',function(err,collection){
            collection.insert(docs,function(err, docs){
                if(err) throw err;
                else {
                    collection.find({tags:['fruit','food','citrus']}).toArray(function(err,docs){
                        if(err) throw err;
                        else {
                            console.log(docs);
                            db.close();
                        }
                    })
                }
            })
        })
    })

    /* 除了可以指定数组完整内容外。还可以单独指定字段值数组中包含的某个元素 */
    {'tags':'citrus'}

    /* 使用数组中的序号来精确指定字段值数组(第一个元素的序号为0) */

    {'tags.0':'fruit'}

    指定某个子数据文档的某个元素的查询条件

    "use strict"
    const util = require('util');
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    let food1 = {type:"food",price:11};
    let food2 = {type:"food",price:10};
    let food3 = {type:"food",price:9};
    let food4 = {type:"food",price:8};
    let food = [food1,food2,food3,food4];
    let store1 = {name:"store1",goods:food};
    
    let book1 = {type:"book",price:11};
    let book2 = {type:"book",price:10};
    let book3 = {type:"book",price:9};
    let book4 = {type:"book",price:8};
    let book = [book1,book2,book3,book4];
    let store2 = {name:"store2",goods:book};
    
    var storesArray = [store1,store2];
    
    var db = new mongo.Db('node-mogo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,data){
        db.collection('stores',function(err,collection){
            collection.insert(storesArray,function(err, docs){
                if(err) throw err;
                else {
                    collection.find({'goods.type':"book"}).toArray(function(err,docs){
                        if(err) throw err;
                        else {
                            console.log(util.inspect(docs,{depth:3}));
                            db.close();
                        }
                    })
                }
            })
        })
    })

    /* 小于$lt */
    {'goods.price':{$lt:10}}

    /* 倒序排列,从大到小 */
    /* {},{sort:{price:-1}} */

    /* limit */
    {},{limit:1}

    /* explain 查看性能 */
    {},{explain:true}

     指定在查询时利用根据price 字段 创建的索引

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    
    let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,db){
        db.collection('goods',function(err,collection){
           collection.createIndex({price:1},function(err, indexName){
                if(err) throw err;
                else {
                    collection.find({type:'food'},{hint:{price:1}}).toArray(function(err,docs){
                        if(err) throw err;
                        else {
                            console.log(docs);
                            db.close();
                        }
                    })
                }
            })
        })
    })

     查询一条数据findOne

    "use strict"
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    
    let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,db){
        db.collection('goods',function(err,collection){
           collection.findOne({},function(err , docs){
                   console.log(docs);
                   db.close();
           })
        })
    })

     Update 更新数据

    "use strict"
    const util = require('util');
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,db)
    {
        db.collection('users',function(err,collection){
        /* {}默认只更新第一条,可能是为了安全考虑考虑吧 */
            collection.update({},{username:"test",nickname:"test"},function(err,result){
                  if(err) throw err;

             let n = JSON.parse(result).n;
             console.log(`更新了${n}条记录`);

                  collection.find({}).toArray(function(err,docs){
                          console.log(docs);
                  })
            })  
        })
    })

    /* 指定更新条件 */
    {username:"Lee"},{username:"李钊鸿",nickname:"test"}

     删除数据

    "use strict"
    const util = require('util');
    const mongo = require('mongodb');
    const host = "localhost";
    const port = 27017;
    
    let db = new mongo.Db('node-mongo-examples',new mongo.Server(host,port,{auto_reconnect:true}),{safe:true});
    db.open(function(err,db)
    {
        db.collection('users',function(err,collection){
            collection.remove({username:"test"},function(err,result){
                  if(err) throw err;
                  let n = JSON.parse(result).n;
                  console.log(`更新了${n}条记录`);
                  collection.find({}).toArray(function(err,docs){
                          console.log(docs);
                  })
            })  
        })
    })
  • 相关阅读:
    将已排序的数组乱序
    Roadmap!!
    测试
    最大对称字串
    约瑟夫环问题
    大家好
    MYSQL数据库导入SQL文件出现乱码如何解决
    Hibernate缓存
    Spring备忘四(涵盖Spring2.5)
    Struts2 Hello,Wold
  • 原文地址:https://www.cnblogs.com/CyLee/p/5886009.html
Copyright © 2011-2022 走看看