zoukankan      html  css  js  c++  java
  • mongodb学习总结

    mongodb学习总结

    一丶什么是MongoDB

      MongoDB是一个基于分布式文件存储的数据库, 由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案.MongoDB是一个结余关系数据库和非关系数据库之间的产品, 是非关系数据库当中功能最丰富,最像关系数据库的.

     二丶MongoDB的基本概念

      MongoDB将数据存储为一个文档, 数据结构由键值(key=>value)对组成.

      MongoDB文档类似于JSON对象. 字段值可以包含其他文档, 数组及文档数组.

    {
        "name":"timfruit",
        "age": 24,
        "hobby":["pingpong", "note"]
    }

      MongoDB中的基本概念是文档丶集合丶数据库.

      MongoDB是面向文档的数据库, MongoDB中的文档相当于Mysql表中的一行数据, MongoDB中的文档是保存在集合中的, 向集合中插进一份文档, 相当于向MySql表中插入一行数据, 也就是说MongoDB中的集合类似于Mysql中的表.Mongodb的集合是保存在数据库中的, 在MongoDB的数据库中创建一个集合, 相当于在Mysql中database中创建一个

       

    三丶mongodb的基本操作(CRUD)

      请先自行安装mongodb

      在linux安装mongodb

      在windows安装mongodb  

      -- 运行mongod服务

      -- 运行mongo客户端(可与服务进行交互)

       mongo客户端的一些参数用法:

       3.1)查看数据库

      

       show dbs 查看所有数据库

      db  查看正在使用的数据库

      3.2) 创建MongoDB数据库

      use <database> 并没有真正创建数据库, 而是插入了一些数据之后, 才会创建数据库和集合

      3.3) 插入文档

    db.inventory.insertOne(
       { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
    )

      查看结果

      插入多份文档

    db.inventory.insertMany([
       { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
       { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
       { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
    ])

      db.collection.insert()插入一份或者多份文档

      3.4) 查询文档

       准备数据

    db.inventory.insertMany([
       { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
       { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
       { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
       { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
    ]);

      a) 查询所有数据

    db.inventory.find( {} )

      相当于sql

    SELECT * FROM inventory

      b) 精确的等值查询

      精确的等值条件可以使用{<field1>: <value1>, ... }

    db.inventory.find( { status: "D" } )

      相当于SQL

    SELECT * FROM inventory WHERE status = "D"

      查询过滤器, 即查询条件的写法形式, 等值形式, <field>:<value>, 条件查询里的操作符形式 <field>: {<operator>: <value>}

      c)使用操作符进行条件查询

      条件查询操作符形式: { <field1>: { <operator1>: <value1> }, ... }

    db.inventory.find( { status: { $in: [ "A", "D" ] } } )

      相当于SQL

    SELECT * FROM inventory WHERE status in ("A", "D")

      d) 精准 AND 条件  查询

      查询inventory集合中status="A" 而且 qty<30的文档:

    db.inventory.find( { status: "A", qty: { $lt: 30 } } )

      相当于SQL

    SELECT * FROM inventory WHERE status = "A" AND qty < 30

       e)精准 OR 条件 查询

       {$or: [   {<field>:<value>, <field>:{<operator>: <value>}}    }

       查询inventory中status="A" 或者 qty<30的文档

    db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

       相当于SQL

    SELECT * FROM inventory WHERE status = "A" OR qty < 30

      f) AND , OR 混合查询

    db.inventory.find( {
         status: "A",
         $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
    } )

       相当于SQL

    SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

      一些常用的操作符

     

      g) 投影, 指定返回值

    db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

      相当于SQL:

    SELECT _id, item, status from inventory WHERE status = "A"

       3.5)更新修改文档

       准备数据

    db.inventory.insertMany( [
       { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
       { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
       { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
       { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
       { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
       { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
       { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
       { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
    ] );

      a) 在一个集合里更新文档

      db.collection.update()

      db.collection.findAndModify()

    {
      <update operator>: { <field1>: <value1>, ... },
      <update operator>: { <field2>: <value2>, ... },
      ...
    }

      更新文档的常用操作符

       将item属性为paper的文档 中的"com.uom"属性设置为"cm", "status"属性设置为"P",  添加lastModified属性的字段, 并设置为$currentDate当前时间.

    db.inventory.updateOne(
       { item: "paper" },
       {
         $set: { "size.uom": "cm", status: "P" },
         $currentDate: { lastModified: true }
       }
    )

       

      修改的结果为:

     

      b) 在一个集合里修改多份文档

      将所有qty<50的文档, 修改对应值, 增加修改时间字段

    db.inventory.updateMany(
       { "qty": { $lt: 50 } },
       {
         $set: { "size.uom": "in", status: "P" },
         $currentDate: { lastModified: true }
       }
    )

      c) 替换文档

      将item为paper的文档, 替换成指定文档.

    db.inventory.replaceOne(
       { item: "paper" },
       { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
    )

       

      修改之前:

      修改之后:

       d)修改字段名:

      {$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

      将item为canvas的文档中的"status"属性名 改为 "newstatus"

     db.inventory.update({item:"canvas"},{$rename:{"status":"newstatus"}})  

      修改结果为:

      3.6) 删除文档

      清空之前的数据:   db.inventory.remove({})

      准备数据:

    db.inventory.insertMany( [
       { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
       { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
       { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
       { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
    ] );

      a) 删除匹配的多份文档中的第一份文档

    db.inventory.deleteOne({status:"A"})

      b) 删除匹配的多份文档

    db.inventory.deleteMany({status:"D"})

      c) 删除所有

    db.inventory.deleteMany({})

      3.7) 批量写

       db.collection.bulkWrite()提供批量插入,更新,删除的操作.MongoDb的批量插入也可以通过db.collection.insertMany()方法.

       bulk wirte操作可以是有序的(ordered), 也可以是无序的(unordered).

       有序执行一系列的操作, MongoDB将会串行执行. 一旦发生一个操作出错, MongoDB将会立即返回.

      无序执行一系列的操作, MongoDB可以并行执行,但行为不能被保证. 如果出错, MongoDB将会继续执行.

      在分片集合中执行一批有序操作, 将会比无序操作更慢, 因为有序操作需要串行等待执行.

       准备数据:

    db.inventory.insertMany([
        { "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 },
        { "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 },
        { "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }
        ]);

      将一系列操作批量执行 :

    db.characters.bulkWrite(
          [
             { insertOne :
                {
                   "document" :
                   {
                      "_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
                   }
                }
             },
             { insertOne :
                {
                   "document" :
                   {
                      "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
                   }
                }
             },
             { updateOne :
                {
                   "filter" : { "char" : "Eldon" },
                   "update" : { $set : { "status" : "Critical Injury" } }
                }
             },
             { deleteOne :
                { "filter" : { "char" : "Brisbane"} }
             },
             { replaceOne :
                {
                   "filter" : { "char" : "Meldane" },
                   "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
                }
             }
          ]
       );

       返回结果为:

    {
        "acknowledged" : true,
        "deletedCount" : 0,
        "insertedCount" : 2,
        "matchedCount" : 0,
        "upsertedCount" : 0,
        "insertedIds" : {
            "0" : 4,
            "1" : 5
        },
        "upsertedIds" : {
            
        }
    }

       3.7)在配置复制集时的读隔离级别

    四丶聚合操作

       聚合操作处理多条数据记录和返回计算结果

      1) 聚合pipeline

       准备数据:

    db.inventory.insertMany( [
       { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
       { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
       { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
       { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
       { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
       { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
       { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
       { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
       { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
    ] );

       使用格式为

    db.collection.aggregate( [ { <stage> }, ... ] )

       a)使用案例1

      查询所有qty属性值小于100的文档, 并返回所有"qty"的值

    db.inventory.aggregate([
        {$match:{ "qty":{"$lt":100} }},
        {$project: {"qty":1} }  
    ]);

      $match: 为匹配stage, 值可以是正常的查询语句

      $project: 为投影stage, 值是指定需要返回的属性

      输出结果为:

      

       b) 使用案例2

      对所有"qty"值小于100的文档, 以"status"分组, 并计算"qty"的总数

    db.inventory.aggregate([
        {$match:{ "qty":{"$lt":100} }}, 
        {$group: {_id:"$status", total: {"$sum": "$qty"} }  } 
     ]);

      结果为:

      一些常用聚合stage:

      2) map-reduce

    五丶索引

       mongo的索引和其他数据库的索引类似,用于加快查询.

       1. 创建索引

    db.collection.createIndex( <key and index type specification>, <options> )

      举例,

    db.mycol.createIndex( { name: -1 } )

      如果集合mycol中的name字段没有一样的索引定义, 将创建该索引

      2. 索引名字

      使用{ item : 1, quantity: -1 }语句创建索引, 默认索引名字为item_1_quantity_-1

       使用如下语句, 可以指定索引名字

    db.products.createIndex(
      { item: 1, quantity: -1 } ,
      { name: "query for inventory" }
    )

       3. 查看索引

    db.mycol.getIndexes()

      4. 删除索引

      删除在属性"tx-id"上的索引

    db.accounts.dropIndex( { "tax-id": 1 } )

      删除集合的所有索引

    db.mycol.dropIndexes()

       5. 索引类型

     六丶Mongodb界面工具

      本人使用nosqlbooster , 因为它跨平台

      

    人生没有彩排,每一天都是现场直播
  • 相关阅读:
    CSS选择器
    CSS的语法规范
    CSS简介
    spring 工厂模式解耦的升级版(多例转单例)
    Html label标签
    Java 多线程入门详解
    Html 表单
    Html 列表
    web项目的建立(idea版本)
    工厂模式详解
  • 原文地址:https://www.cnblogs.com/timfruit/p/11516381.html
Copyright © 2011-2022 走看看