zoukankan      html  css  js  c++  java
  • Monggodb基础

    MongoDB 查询文档使用 find() 方法。

    find() 方法以非结构化的方式来显示所有文档。

    mongodb的find().pretty()方法的作用。

    使得查询出来的数据在命令行中更加美观的显示,不至于太紧凑。

    语法

    MongoDB 查询数据的语法格式如下:

    db.collection.find(query, projection)
    • query :可选,使用查询操作符指定查询条件
    • projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

    MongoDB 与 RDBMS Where 语句比较

    如果你熟悉常规的 SQL 数据,通过下表可以更好的理解 MongoDB 的条件语句查询:

    操作格式范例RDBMS中的类似语句
    等于 {<key>:<value>} db.col.find({"by":"菜鸟教程"}).pretty() where by = '菜鸟教程'
    小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
    小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
    大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
    大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
    不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

    MongoDB AND 条件

    MongoDB 的 find() 方法可以传入多个键(key),每个键(key)以逗号隔开,即常规 SQL  的 AND 条件。

    语法格式如下:

    >db.col.find({key1:value1, key2:value2}).pretty()

    MongoDB OR 条件

    MongoDB OR 条件语句使用了关键字 $or,语法格式如下:

    >db.col.find(
       {
          $or: [
             {key1: value1}, {key2:value2}
          ]
       }
    ).pretty()


    AND 和 OR 联合使用



    日期查询


    MongoDB 日期查询目前可通过Date 和ISODate两种方式: 1.Date方式,2.ISODate方式,查询大于等于北京时间2013年2月25日0点的数据记录数方法为,MongoDB中的格式是标准时间,相差8小时:
     
    MongoDB的面向文档(document-oriented)设计中采用更为灵活的文档来作为数据模型用来取代RDBMS中的行,面向文档的设计让开发人员获取数据的方式更加灵活,甚至于开发人员仅用一条语句即可查询复杂的嵌套关系,让开发人员不必为了获取数据而绞尽脑汁。它可以是实现高并发,适用于大数据领域。
    传统数据库设计思维中,项目的设计阶段需要对数据库表中的字段名称、字段类型、进行规定,如果尝试插入不符合设计的数据,数据库不会接受这条数据以保证数据的完整性。
    NoSQL采用的是对集合(类似"表")中的文档(类似于"行")进行动态追加,在创建集合之初不会对数据类型进行限定,任何文档都可以追加到任何集合中去.,但种类很多的字段单独设计一张表,可以将他们集中在单独一张表进行存储,但这样做的弊病也是显而易见的,我们在获取数据时需要对同一张表的不同文档进行区分,增加了开发上的代码量。所以在设计之初需要权衡动态模式的优劣来选择表中的数据类型。
     
    MongoDB不支持事务,现在众多的软件依旧需要事务的管理,所以对于事务一致性要求较高的程序只能在软件层面进行管理,而无法从数据库进行管理。

    database ==> 数据库;

    collection ==> 集合(表);

    document ==> 文档(数据记录);

    field ==> 域(数据字段);

    index ==> 索引;

    primary key ==> 主键,MongoDB自动将_id字段设置为主键。


    创建数据库
    use databasename
    如:
    > db.getName()
    test
    > use mongotest
    switched to db mongotest
    > show dbs;
    admin   0.000GB
    config  0.000GB
    local   0.000GB
    > db
    mongotest
    可以看到,我们刚创建的数据库 mongotest并不在数据库的列表中, 要显示它,我们需要向 mongotest数据库插入一些数据。
    > db.mongotest.insert({"id":10001,"name":"tianyongtao","regtime":Date()})
    WriteResult({ "nInserted" : 1 })
    > show dbs
    admin      0.000GB
    config     0.000GB
    local      0.000GB
    mongotest  0.000GB
    删除数据库
    > use test510
    switched to db test510
    > db.test510.insert({"id":222,"name":"tianyongtao"})
    WriteResult({ "nInserted" : 1 })
    > db.test510
    test510.test510
    > db.dropDatabase()
    { "dropped" : "test510", "ok" : 1 }
    -------------------------------------------------
    添加数据集删除数据集
    > use mongo510
    switched to db mongo510
    > db.mongo510.insert({"id":001,"name":"tianyt"})
    WriteResult({ "nInserted" : 1 })
    > show dbs
    admin     0.000GB
    config    0.000GB
    local     0.000GB
    mongo510  0.000GB

    MongoDB 中使用 createCollection() 方法来创建集合。

    语法格式:db.createCollection(name, options)  参数说明:  name: 要创建的集合名称   options: 可选参数, 指定有关内存大小及索引的选项、

    > db.createCollection("userinfo")
    { "ok" : 1 }
    > db
    mongo510
    > show collections
    mongo510
    userinfo

     

    在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。

    > db.createCollection("recharge")
    { "ok" : 1 }
    > show collections
    mongo510
    recharge
    userinfo

    > db.recharge.drop()
    true
    > show collections
    mongo510
    userinfo

     

     

    文档的数据结构和 JSON 基本一样。

    所有存储在集合中的数据都是 BSON 格式。

    BSON 是一种类似 JSON 的二进制形式的存储格式,是 Binary JSON 的简称。

    > db.userinfo.insert({"id":001,"name":"liu"})
    WriteResult({ "nInserted" : 1 })

    > db.userinfo.insert({"id":001,"name":"liu","regdate":"2019-05-10 15:35"})
    WriteResult({ "nInserted" : 1 })

    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }

    > db.userinfo.find({},{"name":1,"regdate":1})
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "name" : "liu", "regdate" : "2019-05-10 15:35" }

     > db.userinfo.find({},{"name":1,"regdate":1,_id:false})
    { "name" : "liu" }
    { "name" : "liu", "regdate" : "2019-05-10 15:35" }
    > db.userinfo.find({},{"name":1,"regdate":1,_id:0})
    { "name" : "liu" }
    { "name" : "liu", "regdate" : "2019-05-10 15:35" }

     

    也可以将数据定义为一个变量,然后将文档插入

    > doc510={id:56,name:"ma",regdate:"2019-05-10 18:01"}
    { "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    > db.userinfo.insert(doc510)
    WriteResult({ "nInserted" : 1 })
    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }

     

    > db.userinfo.find({"id":{$gt:50}})
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }

     

    插入文档你也可以使用 db.col.save(document) 命令。如果不指定 _id 字段 save() 方法类似于 insert() 方法。如果指定 _id 字段,则会更新该 _id 的数据。

     

    •  db.collection.insertOne():向指定集合中插入一条文档数据
    •  db.collection.insertMany():向指定集合中插入多条文档数据

     

    > db.userinfo.insertOne(doc5101)
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("5cd552af02d3c2a6078c8c52")
    }
    > db.userinfo.insertOne(doc5102)
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("5cd552b602d3c2a6078c8c53")
    }
    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5526d02d3c2a6078c8c51"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552af02d3c2a6078c8c52"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552b602d3c2a6078c8c53"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }

    > db.userinfo.insertMany([doc5101,doc5102])
    {
            "acknowledged" : true,
            "insertedIds" : [
                    ObjectId("5cd552e002d3c2a6078c8c54"),
                    ObjectId("5cd552e002d3c2a6078c8c55")
            ]
    }
    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5526d02d3c2a6078c8c51"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552af02d3c2a6078c8c52"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552b602d3c2a6078c8c53"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c54"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c55"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }

     

     

    一次插入多条数据

    1、先创建数组

    2、将数据放在数组中

    3、一次 insert 到集合中


    > var arr=[]
    > for(var i=1;i<10;i++){
    ... arr.push({id:i,name:i})
    ... }
    9

    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5526d02d3c2a6078c8c51"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552af02d3c2a6078c8c52"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552b602d3c2a6078c8c53"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c54"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c55"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c56"), "id" : 1, "name" : 1 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : 6 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : 7 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : 8 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }

     

    id大于5小于等于9,并且name在6,9中的数据

    > db.userinfo.find({id:{$gt:5,$lte:9},"name":{$in:[6,9]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : 6 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }

     

     

    MongoDB 使用 update() 和 save() 方法来更新集合中的文档。

    update() 方法

    update() 方法用于更新已存在的文档。语法格式如下:

    db.collection.update(
       <query>,
       <update>,
       {
         upsert: <boolean>,
         multi: <boolean>,
         writeConcern: <document>
       }
    )

    参数说明:

    • query : update的查询条件,类似sql update查询内where后面的。
    • update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
    • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
    • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
    • writeConcern :可选,抛出异常的级别。

    > db.userinfo.update({id:{$gt:5,$lte:9},"name":{$in:[6,9]}},{$set:{"name":"tian"}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.userinfo.find({id:{$gt:5,$lte:9},"name":{$in:[6,9]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }
    > db.userinfo.find()
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5526d02d3c2a6078c8c51"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552af02d3c2a6078c8c52"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552b602d3c2a6078c8c53"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c54"), "id" : 560, "name" : "zhou", "regdate" : "2019-05-10 18:06" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c55"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c56"), "id" : 1, "name" : 1 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : 7 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : 8 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }

    > db.userinfo.update({id:{$gt:5,$lte:9},"name":{$in:[7,8]}},{$set:{"name":"tianhaha"}},{multi:true})
    WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

    > db.userinfo.find({id:{$gt:5,$lte:9},"id":{$in:[7,8]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "tianhaha" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "tianhaha" }

    > db.userinfo.update({id:{$gt:5,$lte:9},"id":{$in:[7,8]}},{$set:{"name":"duguqiubai"}},{multi:true})
    WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

    > db.userinfo.find({id:{$gt:5,$lte:9},"id":{$in:[7,8]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "duguqiubai" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "duguqiubai" }

     > db.userinfo.update({id:{$gt:5,$lte:9},"id":{$in:[7,8]}},{$set:{"name":"dongfangbubai"}},true,true)
    WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
    > db.userinfo.find({id:{$gt:5,$lte:9},"id":{$in:[7,8]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "dongfangbubai" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "dongfangbubai" }
    > db.userinfo.update({id:{$gt:5,$lte:9},"id":{$in:[7,8]}},{$set:{"name":"fengqingyang"}},false,true)
    WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
    > db.userinfo.find({id:{$gt:5,$lte:9},"id":{$in:[7,8]}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }

    只更新第一条记录:

    db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

    全部更新:

    db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

    只添加第一条:

    db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

    全部添加进去:

    db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

    全部更新:

    db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );

    只更新第一条记录:

    db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );

    save() 方法

    save() 方法通过传入的文档来替换已有文档。语法格式如下:

    db.collection.save(
       <document>,
       {
         writeConcern: <document>
       }
    )

    参数说明:

    • document : 文档数据。
    • writeConcern :可选,抛出异常的级别。

     删除文档

    db.collection.remove(
       <query>,
       {
         justOne: <boolean>,
         writeConcern: <document>
       }
    )

    参数说明:

    • query :(可选)删除的文档的条件。
    • justOne : (可选)如果设为 true 或 1,则只删除一个文档,如果不设置该参数,或使用默认值 false,则删除所有匹配条件的文档。
    • writeConcern :(可选)抛出异常的级别。

    > db.userinfo.find({id:{$lte:1}})
    { "_id" : ObjectId("5cd54d7502d3c2a6078c8c4e"), "id" : 1, "name" : "liu" }
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c56"), "id" : 1, "name" : 1 }
    > db.userinfo.remove({id:{$lte:1}},true)
    WriteResult({ "nRemoved" : 1 })
    > db.userinfo.find({id:{$lte:1}})
    { "_id" : ObjectId("5cd54dc902d3c2a6078c8c4f"), "id" : 1, "name" : "liu", "regdate" : "2019-05-10 15:35" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c56"), "id" : 1, "name" : 1 }

    > db.userinfo.remove({id:{$lte:1}},false)
    WriteResult({ "nRemoved" : 2 })

    > db.userinfo.find({id:{$gte:561}})
    { "_id" : ObjectId("5cd552b602d3c2a6078c8c53"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    { "_id" : ObjectId("5cd552e002d3c2a6078c8c55"), "id" : 561, "name" : "wang", "regdate" : "2019-05-10 18:08" }
    > db.userinfo.remove({id:{$lte:1}},1)
    WriteResult({ "nRemoved" : 0 })
    > db.userinfo.remove({id:{$gte:561}},1)
    WriteResult({ "nRemoved" : 1 })
    > db.userinfo.remove({id:{$gte:561}},0)
    WriteResult({ "nRemoved" : 1 })
    > db.userinfo.remove({id:{$gte:560}},0)
    WriteResult({ "nRemoved" : 3 })

    语法

    MongoDB 查询数据的语法格式如下:

    db.collection.find(query, projection)
    • query :可选,使用查询操作符指定查询条件
    • projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

    如果你需要以易读的方式来读取数据,可以使用 pretty() 方法,语法格式如下:

    >db.col.find().pretty()

    pretty() 方法以格式化的方式来显示所有文档

    模糊查询

    查询 title 包含"教"字的文档:

    db.col.find({title:/教/})

    查询 title 字段以"教"字开头的文档:

    db.col.find({title:/^教/})

    查询 titl e字段以"教"字结尾的文档:

    db.col.find({title:/教$/})


    $type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果。

    > db.userinfo.find({"name":{$type:2}})
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }
    > db.userinfo.find({"name":{$type:1}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }

    > db.userinfo.find({"name":{$type:'string'}})
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }
    > db.userinfo.find({"name":{$type:'double'}})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }

     

    > db.userinfo.find().limit(2)
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }

     

    MongoDB Skip() 方法

    我们除了可以使用limit()方法来读取指定数量的数据外,还可以使用skip()方法来跳过指定数量的数据,skip方法同样接受一个数字参数作为跳过的记录条数。

    语法

    skip() 方法脚本语法格式如下:

    >db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)


    MongoDB sort() 方法

    在 MongoDB 中使用 sort() 方法对数据进行排序,sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。

    语法

    sort()方法基本语法如下所示:

    >db.COLLECTION_NAME.find().sort({KEY:1})


    > db.userinfo.find().sort({"id":1})
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    > db.userinfo.find().sort({"id":-1})
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma", "regdate" : "2019-05-10 18:01" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }

    MongoDB使用 createIndex() 方法来创建索引。

    语法

    createIndex()方法基本语法格式如下所示:

    >db.collection.createIndex(keys, options)

    语法中 Key 值为你要创建的索引字段,1 为指定按升序创建索引,如果你想按降序来创建索引指定为 -1 即可。

    1、查看集合索引

    db.col.getIndexes()

    2、查看集合索引大小

    db.col.totalIndexSize()

    3、删除集合所有索引

    db.col.dropIndexes()

    4、删除集合指定索引

    db.col.dropIndex("索引名称")
    > db.userinfo.getIndexes()
    [
            {
                    "v" : 2,
                    "key" : {
                            "_id" : 1
                    },
                    "name" : "_id_",
                    "ns" : "mongo510.userinfo"
            }
    ]
    > db.userinfo.createIndex({"id":1})
    {
            "createdCollectionAutomatically" : false,
            "numIndexesBefore" : 1,
            "numIndexesAfter" : 2,
            "ok" : 1
    }
    > db.userinfo.getIndexes()
    [
            {
                    "v" : 2,
                    "key" : {
                            "_id" : 1
                    },
                    "name" : "_id_",
                    "ns" : "mongo510.userinfo"
            },
            {
                    "v" : 2,
                    "key" : {
                            "id" : 1
                    },
                    "name" : "id_1",
                    "ns" : "mongo510.userinfo"
            }
    ]
    > db.userinfo.dropIndexes()
    {
            "nIndexesWas" : 2,
            "msg" : "non-_id indexes dropped for collection",
            "ok" : 1
    }


    > db.userinfo.find({},{"_id":0,"id":1,"name":2})
    { "id" : 56, "name" : "ma" }
    { "id" : 2, "name" : 2 }
    { "id" : 3, "name" : 3 }
    { "id" : 4, "name" : 4 }
    { "id" : 5, "name" : 5 }
    { "id" : 6, "name" : "tian" }
    { "id" : 7, "name" : "fengqingyang" }
    { "id" : 8, "name" : "fengqingyang" }
    { "id" : 9, "name" : 9 }
    > db.userinfo.find({},{"_id":false,"id":1,"name":2})
    { "id" : 56, "name" : "ma" }
    { "id" : 2, "name" : 2 }
    { "id" : 3, "name" : 3 }
    { "id" : 4, "name" : 4 }
    { "id" : 5, "name" : 5 }
    { "id" : 6, "name" : "tian" }
    { "id" : 7, "name" : "fengqingyang" }
    { "id" : 8, "name" : "fengqingyang" }
    { "id" : 9, "name" : 9 }
    > db.userinfo.find({},{"id":1,"name":2})
    { "_id" : ObjectId("5cd5502202d3c2a6078c8c50"), "id" : 56, "name" : "ma" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c57"), "id" : 2, "name" : 2 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c58"), "id" : 3, "name" : 3 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c59"), "id" : 4, "name" : 4 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5a"), "id" : 5, "name" : 5 }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5b"), "id" : 6, "name" : "tian" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5c"), "id" : 7, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5d"), "id" : 8, "name" : "fengqingyang" }
    { "_id" : ObjectId("5cd5550f02d3c2a6078c8c5e"), "id" : 9, "name" : 9 }  

    MongoDB 聚合

    MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果。有点类似sql语句中的 count(*)。


    aggregate() 方法

    MongoDB中聚合的方法使用aggregate()。

    语法

    aggregate() 方法的基本语法格式如下所示:

    >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

    管道的概念

    管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。

    MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。

    表达式:处理输入文档并输出。表达式是无状态的,只能用于计算当前聚合管道的文档,不能处理其它的文档。

    这里我们介绍一下聚合框架中常用的几个操作:

    • $project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。
    • $match:用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
    • $limit:用来限制MongoDB聚合管道返回的文档数。
    • $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
    • $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
    • $group:将集合中的文档分组,可用于统计结果。
    • $sort:将输入文档排序后输出。
    • $geoNear:输出接近某一地理位置的有序文档。

    例子:id<50后按id分组求数量

    > db.userinfo.aggregate([{$match:{"id":{$lt:50}}},{$group:{"_id":{id:"$id"},count:{$sum:1}}}])
    { "_id" : { "id" : 9 }, "count" : 1 }
    { "_id" : { "id" : 8 }, "count" : 1 }
    { "_id" : { "id" : 7 }, "count" : 1 }
    { "_id" : { "id" : 6 }, "count" : 1 }
    { "_id" : { "id" : 2 }, "count" : 1 }
    { "_id" : { "id" : 5 }, "count" : 3 }
    { "_id" : { "id" : 3 }, "count" : 2 }
    { "_id" : { "id" : 4 }, "count" : 1 }

    > db.userinfo.aggregate([{$match:{"id":{$lt:50}}},{$group:{"_id":{id:"$id"},count:{$sum:1}}},{$project:{"_id":0,"id":"$_id.id","count":"$count"}}])
    { "id" : 9, "count" : 1 }
    { "id" : 8, "count" : 1 }
    { "id" : 7, "count" : 1 }
    { "id" : 6, "count" : 1 }
    { "id" : 2, "count" : 1 }
    { "id" : 5, "count" : 3 }
    { "id" : 3, "count" : 2 }
    { "id" : 4, "count" : 1 }

    相当于sql:select id,count(1) as count from userinfo where id<50 group by id;

    > db.userinfo.aggregate([{$match:{"id":{$lt:50}}},{$group:{"_id":{id:"$id"},arr:{$push:"$name"}}}])
    { "_id" : { "id" : 9 }, "arr" : [ 9 ] }
    { "_id" : { "id" : 8 }, "arr" : [ "fengqingyang" ] }
    { "_id" : { "id" : 7 }, "arr" : [ "fengqingyang" ] }
    { "_id" : { "id" : 6 }, "arr" : [ "tian" ] }
    { "_id" : { "id" : 2 }, "arr" : [ 2 ] }
    { "_id" : { "id" : 5 }, "arr" : [ 5, "liu", "xiaoma" ] }
    { "_id" : { "id" : 3 }, "arr" : [ 3, "dan" ] }
    { "_id" : { "id" : 4 }, "arr" : [ 4 ] }
    > db.userinfo.aggregate([{$match:{"id":{$lt:50}}},{$group:{"_id":"$id",arr:{$push:"$name"}}}])
    { "_id" : 9, "arr" : [ 9 ] }
    { "_id" : 8, "arr" : [ "fengqingyang" ] }
    { "_id" : 7, "arr" : [ "fengqingyang" ] }
    { "_id" : 6, "arr" : [ "tian" ] }
    { "_id" : 2, "arr" : [ 2 ] }
    { "_id" : 5, "arr" : [ 5, "liu", "xiaoma" ] }
    { "_id" : 3, "arr" : [ 3, "dan" ] }
    { "_id" : 4, "arr" : [ 4 ] }

    > db.userinfo.aggregate([{$match:{"id":{$lt:50}}},{$group:{"_id":"$id",arr:{$addToSet:"$name"}}}])
    { "_id" : 9, "arr" : [ 9 ] }
    { "_id" : 8, "arr" : [ "fengqingyang" ] }
    { "_id" : 7, "arr" : [ "fengqingyang" ] }
    { "_id" : 6, "arr" : [ "tian" ] }
    { "_id" : 2, "arr" : [ 2 ] }
    { "_id" : 5, "arr" : [ "xiaoma", "liu", 5 ] }
    { "_id" : 3, "arr" : [ "dan", 3 ] }
    { "_id" : 4, "arr" : [ 4 ] }

  • 相关阅读:
    pytest学习Pytest基础
    Docker基础认识
    DNS 域名解析协议
    Python从数据库取数据到Excel
    PO设计模式
    unittest多种加载执行用例方法
    Dev XtraGridView 添加行时滚动条(界面)随焦点滚动
    阅读器关闭时READ的尝试无效 真正原因 测试通过解决办法
    转帖 用SQL语句 查看 某一存储过程 所带参数
    转 C#多线程及控制线程数量,对for循环输出效率
  • 原文地址:https://www.cnblogs.com/playforever/p/10437599.html
Copyright © 2011-2022 走看看