Mongodb官方文档学习(一)

  • 特性
    • 一种文档数据库(BSON documents)
    • 高性能、丰富的查询语言、高可用、横向扩展、支持多存储引擎
  • Shell(js接口)
    • Date:
      • Date(),返回当前时间的String
      • new Date(),返回Date,通过ISODate()的包装器
      • ISODate(),ISODate(“2012-12-19T06:01:17.171Z”)
    • 检查类型:mydoc._id instanceof ObjectId
    • show dbs,use ,show users
    • gt g t 、 gte(大于等于)、 lt l t 、 lte
  • CRUD操作

    • 插入
      • collection 不存在会自动创建
      • 插入无_id字段时会自动创建
      • db.collection.insertOne() :db. users. insertOne({name: “sue”,age: 26,status: “pending”}
      • db.collection.insertMany() :
    • 查找:db.collection.find()

      • db.inventory.find( { status: “D” } )
      • 嵌入文档查询条件:db.inventory.find( { “size.uom”: “in” } )
      • 数组
        • db.inventory.find( { tags: [“red”, “blank”] } ),包含
        • db.inventory.find( { tags: { $all: [“red”, “blank”] } } ),都包含且没有其他的元素
      • 返回值:db.inventory.find( { status: “A” }, { item: 1, status: 1, _id: 0 } ),等同于SELECT item, status from inventory WHERE status = “A”
      • sort、skip、limit、comunt
        db.inventory.find( { status: { $in: [ "A", "D" ] } } )
        db.inventory.find( {
         status: "A",
         $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
        } )
        db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
    • 更新

      • db.collection.updateOne()
      • db.collection.updateMany()
      • db.collection.replaceOne()
      • 其他能起到更新效果的方法:
        • db.collection.findOneAndReplace().
        • db.collection.findOneAndUpdate().
        • db.collection.findAndModify().
        • db.collection.save().
        • db.collection.bulkWrite().
    • 删除

      • db.collection.deleteOne()
      • db.collection.deleteMany()
      • 其他方法:
        • db.collection.findOneAndDelete().
        • db.collection.findAndModify().
        • db.collection.bulkWrite().
          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" } }
          ])
    • 对比

    SQL Terms/ConceptsMongoDB Terms/Concepts
    databasedatabase
    tablecollection
    rowdocument or BSON document
    columnfield
    indexindex
    table joins$lookup, embedded documents
    primary key(Specify any unique column or column combination as primary key.)primary key (In MongoDB, the primary key is automatically set to the _id field.)
    aggregation (e.g. group by)aggregation pipeline
    transactionstransactions
    • 文本搜索

      • 文本索引:db.stores.createIndex( { name: “text”, description: “text” } )
      • 搜索:db.stores.find( { text: { text: { search: “java coffee shop” } } )
      • 聚合管道的文本搜索
      db.articles.aggregate(
         [
           { $match: { $text: { $search: "cake" } } },
           { $group: { _id: null, views: { $sum: "$views" } } }
         ]
      )
    • 地理位置(GEO)

      • GeoJSON Point
      location: {
            type: "Point",
            coordinates: [-73.856077, 40.848447]
      }
  • 聚合(Aggregation,这个可以点进去看一下)

    • 管道聚合(Aggregation Pipeline)

      • db.aggregate( [ { }, … ] )
      • Operator Expressions
        • Arithmetic Expression Operators: abs, a b s , add, ln, l n , mod,$power……
        • Array Expression Operators: in, i n , range,$size……
        • Boolean Expression Operators: and, a n d , not,$or
        • Comparison Expression Operators: cmp, c m p , eq(equal), gt, g t , gte, lt, l t , lte,$ne(not equal)
        • Conditional Expression Operators
        • Date Expression Operators
      • 比较
      SQL Terms, Functions, and ConceptsMongoDB Aggregation Operators
      WHERE$match
      GROUP BY$group
      HAVING$match
      SELECT$project
      ORDER BY$sort
      LIMIT$limit
      SUM()$sum
      COUNT() sum, s u m , sortByCount
      join$lookup
      • 示例

        {//orders
          cust_id: "abc123",
          ord_date: ISODate("2012-11-02T17:04:11.102Z"),
          status: 'A',
          price: 50,
          items: [ { sku: "xxx", qty: 25, price: 1 },
                   { sku: "yyy", qty: 25, price: 1 } ]
        }
        SELECT COUNT(*) AS count FROM orders
        db.orders.aggregate( [
           {
             $group: {
                _id: null,
                count: { $sum: 1 }
             }
           }
        ] )

        SELECT cust_id,
        SUM(price) as total
        FROM orders
        WHERE status = 'A'
        GROUP BY cust_id
        db.orders.aggregate( [
         { $match: { status: 'A' } },
         {
         $group: {
          _id: "$cust_id",
         total: { $sum: "$price" }
         }
         },
         { $match: { total: { $gt: 250 } } }
        ] )
  • map-reduce
    //案例:计算每个单位订单中数量的平均值(Calculate Order and Total Quantity with Average Quantity Per Item)
    {// collection orders
     _id: ObjectId("50a8240b927d5d8b5891743c"),
     cust_id: "abc123",
     ord_date: new Date("Oct 04, 2012"),
     status: 'A',
     price: 25,
     items: [ { sku: "mmm", qty: 5, price: 2.5 },
              { sku: "nnn", qty: 5, price: 2.5 } ]
    }
    //提交(key,value),对每个items数组提取sku作为key,qty作为value数组的一个字段,count初始化为1
    var mapFunction2 = function() {
                       for (var idx = 0; idx < this.items.length; idx++) {
                           var key = this.items[idx].sku;
                           var value = {
                                         count: 1,
                                         qty: this.items[idx].qty
                                       };
                           emit(key, value);
                       }
                    };
    // 对每个key,合并value               
    var reduceFunction2 = function(keySKU, countObjVals) {
                     reducedVal = { count: 0, qty: 0 };

                     for (var idx = 0; idx < countObjVals.length; idx++) {
                         reducedVal.count += countObjVals[idx].count;
                         reducedVal.qty += countObjVals[idx].qty;
                     }

                     return reducedVal;
                  };
    // 对每个key,计算订单中数量的平均值              
    var finalizeFunction2 = function (key, reducedVal) {

                       reducedVal.avg = reducedVal.qty/reducedVal.count;

                       return reducedVal;

                    };
    // query 条件                
    db.orders.mapReduce( mapFunction2,
                     reduceFunction2,
                     {
                       out: { merge: "map_reduce_example" },
                       query: { ord_date:
                                  { $gt: new Date('01/01/2012') }
                              },
                       finalize: finalizeFunction2
                     }
                   )                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值