MonogoDb學習筆記


最近重新學習了Mongodb,總結下了Monogodb的用法,以便以后查看。

備份:
   mongodump -h 127.0.0.1 -d spm -o /home/liuwei
還原:
   mongorestore -h dbhost -d dbname -directoryperdb /home/liuwei/spm
顯示所有數據庫:
  show dbs;
創建數據庫: 如果數據庫不存在,則創建數據庫,否則切換到指定數據庫。
  use dbname;
刪除數據庫:
  db.dropDatabase();
創建集合: capped 是否固定集合 配合size autoindexid 自動為_id添加索引 max集合中包含文檔的最大數量
  db.createCollection('student');
  db.createCollection("mycol", { capped : true, autoIndexId : true, size : 
   6142800, max : 10000 } )
刪除集合:
 db.student.drop(); 
顯示所有集合
show collections;
插入文檔:
 db.student.insert({code:"201517020119",name:"zhangsan",age:20});
刪除文檔:
 db.student.remove({code:"201517020119"});
更新文檔:
db.update({條件},{更改的值key:value},如果不存在是否新建(true|false-默認),只找匹配的第一條記錄-默認false);

$inc
 db.student.update({"code":"111"},{"$inc":{"age":1}});
 
$set 沒有就新建
 db.student.update({"code":"111"},{"$set":{"score":100}})
 
$unset 刪除字段
 db.student.update({"code":"112"},{"$unset":{"score":11}}) 

$rename  { $rename : { old_field_name : new_field_name } }

$push 往集合的數組中插入數據
 db.student.update({"code":"111"},{"$push":{"books":"數據結構"}})

$pushAll
 db.student.update({"code":"111"},{"$pushAll":{"books":["數據結構","語文"]}})
 
$addToSet 往集合的數組中插入數據 --避免重復
 db.student.update({"code":"111"},{"$addToSet":{"books":["數據結構"]}})
 
$pop 刪除制定位置的元素 -1:頭部  1:末尾
 db.student.update({"code":"111"},{"$pop":{"books":-1}})
 
$pull 刪除指定名稱的數據  
 db.student.update({"code":"111"},{"$pull":{"books":"數據結構"}})

$gt >  $gte >=   $lt <   $lte <=   $ne !=

$in
db.student.find({"code":{"$in":["111","112"]}}); 

$nin
db.student.find({"code":{"$nin":["111","112"]}}); 

$or
db.student.find({"$or":[{"code":"111"},{"code":"112"}]}); 

$mod [n,m] *%n==m
db.student.find({"age":{"$mod":[10,7]}}); 

$not
 db.student.find({"age":{"$not":{"$mod":[10,7]}}});

 正則查詢  i表示忽略大小寫
 db.student.find({"name":/z/i});
 
$all 滿足數組所有元素
 db.student.find({"books":{"$all":["數據結構","語文"]}}); 

$elemMatch 匹配數組的內嵌文檔
db.student.find({"books":{"$elemMatch":{"name":"語文","auth":"zhangsan"}}})

$size 數組的大小
 db.student.find({"books":{"$size":2}});

$slice 返回數組指定記錄條數 [10,3] 返回11~13  -1從后計算
 db.student.find({},{"books":{"$slice":1}}).pretty();
 
游標:
  var students = db.student.find();
  while(students.hasNext()){
   print(students.next().code);
  }

sort() 1從小到大   -1 從大到小
  db.student.find().sort("code":1);

索引:
  ①創建索引  1按照升序  -1 降序
   db.student.ensureIndex({"code":1});
   db.student.ensureIndex({"code":1},{"unique":true}); //唯一索引
  db.student.ensureIndex({"code":1},{"dropDups",true});     Boolean    在建立唯一索引時是否刪除重復記錄,指定 true 創建唯一索引。默認值為 false.
   db.student.ensureIndex({"name":1},{"name":"ind_name"});  //制定名稱
  ②刪除索引  -- db.student.dropIndex( "indexName" ) or db.student.dropIndex( { "indexKey" : 1 } )
   db.student.dropIndex(name); 
   db.studeng.dropIndexs(); // 刪除全部索引
   
   
數量查詢 .count() 
db.student.count({"code":"111"});

查詢分頁:
db.student.find().limit(2),skip(1);
去除重復數據 distant
 db.student.distinct("code")  --> [112,113]
aggregate
   一、group
        1、按照code分組  在返回每一組的總個數
      db.student.aggregate([{$group : {_id : "$code", "age_count" : {"$sum" : 1}}}])
    2、按照code分組  在返回每一組中age的總和
      db.student.aggregate([{$group : {_id : "$code", "age_sum" : {"$sum" : "$age"}}}])
     3、按照code分組  在返回每一組中age的總和 並升序排序    
     db.student.aggregate([{$group : {_id : "$code", "age_max" : {"$max" : "$age"}}},{$sort: {"_id": 1}}])
    總結:$sum $max $min $avg $first $last
   etc:
    $project:修改輸入文檔的結構。可以用來重命名、增加或刪除域,也可以用於創建計算結果以及嵌套文檔。
      db.article.aggregate( { $project : {  "code" : 1 ,  "name" : 1}});
    $match:用於過濾數據,只輸出符合條件的文檔。$match使用MongoDB的標准查詢操作。
    db.articles.aggregate( [  { $match : { score : { $gt : 70, $lte : 90 } } }, { $group: { _id: null, count: { $sum: 1 } } }] );


    $limit:用來限制MongoDB聚合管道返回的文檔數。
    $skip:在聚合管道中跳過指定數量的文檔,並返回余下的文檔。
    db.article.aggregate( { $skip : 5 });
    $unwind:將文檔中的某一個數組類型字段拆分成多條,每條包含數組中的一個值。
    $group:將集合中的文檔分組,可用於統計結果。
    $sort:將輸入文檔排序后輸出。
    $geoNear:輸出接近某一地理位置的有序文檔
    



按日、按月、按年、按周、按小時、按分鍾聚合操作如下:

db.getCollection('m_msg_tb').aggregate(
[
    {$match:{m_id:10001,mark_time:{$gt:new Date(2017,8,0)}}},
    {$group: {
       _id: {$dayOfMonth:'$mark_time'},
        pv: {$sum: 1}
        }
    },
    {$sort: {"_id": 1}}
])    
$dayOfYear: 返回該日期是這一年的第幾天(全年 366 天)。
$dayOfMonth: 返回該日期是這一個月的第幾天(1到31)。
$dayOfWeek: 返回的是這個周的星期幾(1:星期日,7:星期六)。
$year: 返回該日期的年份部分。
$month: 返回該日期的月份部分( 112)。
$week: 返回該日期是所在年的第幾個星期( 053)。
$hour: 返回該日期的小時部分。
$minute: 返回該日期的分鍾部分。
$second: 返回該日期的秒部分(以0到59之間的數字形式返回日期的第二部分,但可以是60來計算閏秒)。
$millisecond:返回該日期的毫秒部分( 0999)。
$dateToString: { $dateToString: { format: , date: } }。


文檔引用:
   {
   "_id":ObjectId("52ffc33cd85242f436000001"), 
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
  }
var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})



explain()
 
    indexOnly: 字段為 true ,表示我們使用了索引。
    cursor:因為這個查詢使用了索引,MongoDB 中索引存儲在B樹結構中,所以這是也使用了 BtreeCursor 類型的游標。
     如果沒有使用索引,游標的類型是 BasicCursor。這個鍵還會給出你所使用的索引的名稱,你通過這個名稱可以查看當前數據庫下的system.indexes集合
     (系統自動創建,由於存儲索引信息,這個稍微會提到)來得到索引的詳細信息。
    n:當前查詢返回的文檔數量。
    nscanned/nscannedObjects:表明當前這次查詢一共掃描了集合中多少個文檔,我們的目的是,讓這個數值和返回文檔的數量越接近越好。
    millis:當前查詢所需時間,毫秒數。
    indexBounds:當前查詢具體使用的索引。

還在繼續完善。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM