1. 程式人生 > >Mongodb-基本命令

Mongodb-基本命令

1.回顧:上篇已經學習過 Mongodb的安裝的兩種方式

2.這篇將學習 mongodb的基本命令

3.準備 :安裝好mongodb後,需要先開啟mongodb服務,後開啟一個客戶端 (cmd操作)

4.建立資料庫,物件和集合

    4.1 新建資料庫  db

use student
    

    4.2 新建集合 Collection

db.createCollection("LABELNET");

    4.3 新建 文件 document

document={"name":"yuan","age":23}

    4.4 檢視所有資料庫
show dbs

    4.5 檢視一個數據庫下的集合狀態

use student;
db.printCollectionStats();
    

    4.6 演示結果:

> use student
switched to db student
> db.createCollection("LABELNET");
{ "ok" : 1 }
> document={"name":"yuan","age":23}
{ "name" : "yuan", "age" : 23 }
> show dbs
local    0.078GB
student  0.078GB
> use student
switched to db student
> db.printCollectionStats();
LABELNET
{
        "ns" : "student.LABELNET",
        "count" : 0,
        "size" : 0,
        "numExtents" : 1,
        "storageSize" : 8192,
        "lastExtentSize" : 8192,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0.
It remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 1,
        "capped" : false,
        "nindexes" : 1,
        "totalIndexSize" : 8176,
        "indexSizes" : {
                "_id_" : 8176
        },
        "ok" : 1
}
---
system.indexes
{
        "ns" : "student.system.indexes",
        "count" : 1,
        "size" : 112,
        "avgObjSize" : 112,
        "numExtents" : 1,
        "storageSize" : 8192,
        "lastExtentSize" : 8192,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0.
It remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 0,
        "capped" : false,
        "nindexes" : 0,
        "totalIndexSize" : 0,
        "indexSizes" : {

        },
        "ok" : 1
}
---
>


5. 插入操作 insert

   5.1 可以先定義一個文件document ,後將文件插入到集合中。或者直接將輸入插入到集合中。

   5.2 基本格式   

             db.集合名稱.insert(已定義的文件);

             db.集合名稱.insert(資料);

   5.3 演示示例

---
> db.LABELNET.insert({"name":"csdn","age":"老大了!"});
WriteResult({ "nInserted" : 1 })
> document={"name":"yuan",age:"23"};
{ "name" : "yuan", "age" : "23" }
> db.LABELNET.insert(document);
WriteResult({ "nInserted" : 1 })

6. 查詢操作 find

   6.1 基本格式

          (1)db.集合名稱.find();顯示文件

          (2)db.集合名稱.find(where);

          (3)db.集合名稱.find({"name":{$type:2}});  

   6.2 基本查詢

> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : "老大了
!" }
{ "_id" : ObjectId("55bec43732cbb5faa25c967d"), "name" : "yuan", "age" : "23" }
   6.3 條件查詢

     $type操作符是基於BSON型別來檢索集合中匹配的結果。

     db.集合名稱.find({"name":{$type:2}});  

     $type 對應得值 有下面幾種:

         Double 1 
	 String 2 
	 Object 3 
	 Array 4 
	 Binary data 5 
	 Object id 7 
	 Boolean 8 
         Date 9 
         Null 10 
         Regular expression 11 
         JavaScript code 13 
         Symbol 14 
         JavaScript code with scope 15 
         32-bit integer 16 
         Timestamp 17 
         64-bit integer 18 
         Min key 255 
         Max key 127 

   演示示例:
> db.LABELNET.find({"name":"yuan"});
{ "_id" : ObjectId("55bec43732cbb5faa25c967d"), "name" : "yuan", "age" : "23" }
> db.LABELNET.find({"name":{$type:2}});
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : "老大了
!" }
{ "_id" : ObjectId("55bec43732cbb5faa25c967d"), "name" : "yuan", "age" : "23" }
>

     6.4  滿足條件的,取固定條數  : db.集合名稱.find({條件}).limit(10);

7.修改資料  update

   7.1基本格式   :  注意條件

    db.集合名稱.update(where,set,未找到插入新的為true,更新多條為true);

   7.2 演示 示例 : 修改 name為csdn的 age值

> db.LABELNET.update({"name":"csdn"},{"$set":{"age":16}},false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55bec43732cbb5faa25c967d"), "name" : "yuan", "age" : "23" }
>
   

    7.3 向集合中的某個文件新增欄位 push

> db.LABELNET.update({"name":"yuan"},{$push:{"csdnBlog":"http://blog.csdn.net/la
blenet"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55bec43732cbb5faa25c967d"), "name" : "yuan", "age" : "23", "
csdnBlog" : [ "http://blog.csdn.net/lablenet" ] }
>
8.刪除操作  remove

   8.1 基本格式

       (1)db.集合名稱.remove(where);        條件刪除

       (2) db.集合名稱.remove();                刪除全部記錄

       (3)  db.集合名稱.drop();                    刪除全部文件(document)


   8.2 演示示例   :條件刪除
> db.LABELNET.remove({"name":"yuan"});
WriteResult({ "nRemoved" : 1 })
> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
>

9. 其他操作 

   9.1 先準備資料

> db.LABELNET.insert({"name":"yuan","age":23});
WriteResult({ "nInserted" : 1 })
> db.LABELNET.insert({"name":"ming","age":10});
WriteResult({ "nInserted" : 1 })
> db.LABELNET.insert({"name":"zhuo","age":30});
WriteResult({ "nInserted" : 1 })
> db.LABELNET.insert({"name":"hpu","age":30});
WriteResult({ "nInserted" : 1 })
> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
{ "_id" : ObjectId("55beca9f32cbb5faa25c9681"), "name" : "hpu", "age" : 30 }
>


   9.1 條件查詢 —— > ,  <  , >= ,<=

      (1)    (>) 大於 - $gt 

      (2)(<) 小於 - $lt 

      (3)(>=) 大於等於 - $gte  

      (4)(<= ) 小於等於 - $lte

  
> db.LABELNET.find({"age":{"$gt":16}});
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
{ "_id" : ObjectId("55beca9f32cbb5faa25c9681"), "name" : "hpu", "age" : 30 }
> db.LABELNET.find({"age":{"$lt":16}});
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
> db.LABELNET.find({"age":{"$gte":16}});
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
{ "_id" : ObjectId("55beca9f32cbb5faa25c9681"), "name" : "hpu", "age" : 30 }
> db.LABELNET.find({"age":{"$lte":16}});
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
> db.LABELNET.find({"age":16});
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
>

   9.2 滿足條件的條數  count

> db.LABELNET.count({"age":30});
2
>

   9.3 得到所有key的value(去掉重複的)   distinct
> db.LABELNET.distinct("age");
[ 16, 23, 10, 30 ]
>

   9.4 檢視集合的資料大小  dataSize  : 注意S 大寫
> db.LABELNET.dataSize();
560
>

   9.5 檢視集合狀態  stats 
> db.LABELNET.stats();
{
        "ns" : "student.LABELNET",
        "count" : 5,
        "size" : 560,
        "avgObjSize" : 112,
        "numExtents" : 1,
        "storageSize" : 8192,
        "lastExtentSize" : 8192,
        "paddingFactor" : 1,
        "paddingFactorNote" : "paddingFactor is unused and unmaintained in 3.0.
It remains hard coded to 1.0 for compatibility only.",
        "userFlags" : 1,
        "capped" : false,
        "nindexes" : 1,
        "totalIndexSize" : 8176,
        "indexSizes" : {
                "_id_" : 8176
        },
        "ok" : 1
}

    9.6 分頁查詢  skip  和 limit   (類似於 linq 操作)
> db.LABELNET.find().skip(2).limit(2);
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
> db.LABELNET.find().skip(0).limit(2);
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
>

    9.7 排序分頁 sort  , skip , limit
> db.LABELNET.find().sort({"age":1}).skip(0).limit(2);
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
> db.LABELNET.find().sort({"age":1}).skip(2).limit(2);
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
>

10.操作函式

   10.1 示例 :插入100 條資料 

> for(var i=0;i<100;i++){var ran=parseInt(i*Math.random());db.LABELNET.insert({"
name":"yuan","age":ran});}
WriteResult({ "nInserted" : 1 })
> db.LABELNET.find();
{ "_id" : ObjectId("55bec40532cbb5faa25c967c"), "name" : "csdn", "age" : 16 }
{ "_id" : ObjectId("55beca3932cbb5faa25c967e"), "name" : "yuan", "age" : 23 }
{ "_id" : ObjectId("55beca4632cbb5faa25c967f"), "name" : "ming", "age" : 10 }
{ "_id" : ObjectId("55beca5132cbb5faa25c9680"), "name" : "zhuo", "age" : 30 }
{ "_id" : ObjectId("55beca9f32cbb5faa25c9681"), "name" : "hpu", "age" : 30 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9682"), "name" : "yuan", "age" : 0 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9683"), "name" : "yuan", "age" : 0 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9684"), "name" : "yuan", "age" : 1 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9685"), "name" : "yuan", "age" : 1 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9686"), "name" : "yuan", "age" : 3 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9687"), "name" : "yuan", "age" : 2 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9688"), "name" : "yuan", "age" : 1 }
{ "_id" : ObjectId("55becfee32cbb5faa25c9689"), "name" : "yuan", "age" : 3 }
{ "_id" : ObjectId("55becfee32cbb5faa25c968a"), "name" : "yuan", "age" : 7 }

   10.2 去某個key的值
> var list=db.LABELNET.find(); list.forEach(function(x){print(x.name);});
csdn
yuan
ming
zhuo
hpu
yuan
yuan
yuan
yuan
yuan
yuan
yuan
yuan
yuan
yuan
yuan
  10.3 效能分析函式  explain

    首先我們查到 age為83的 是最後一條,且僅此一條

{ "_id" : ObjectId("55becfee32cbb5faa25c96e5"), "name" : "yuan", "age" : 83 }
> db.LABELNET.count({"age":83});
1
>

    後我們查詢這個 age為 83 的文件 :
> db.LABELNET.count({"age":83});
1
> db.LABELNET.find({"age":83}).explain()  ;
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "student.LABELNET",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "age" : {
                                "$eq" : 83
                        }
                },
                "winningPlan" : {
                        "stage" : "COLLSCAN",
                        "filter" : {
                                "age" : {
                                        "$eq" : 83
                                }
                        },
                        "direction" : "forward"
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "LABELNET",
                "port" : 27017,
                "version" : "3.0.5",
                "gitVersion" : "8bc4ae20708dbb493cb09338d9e7be6698e4a3a3"
        },
        "ok" : 1
}
>

   11.索引  (非常重要,可提供查詢速度)ensureIndex

        11.1 新增唯一索引

> db.LABELNET.ensureIndex({"name":1},{"unique":true});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "errmsg" : "exception: E11000 duplicate key error index: student.LABELNE
T.$name_1 dup key: { : \"yuan\" }",
        "code" : 11000,
        "ok" : 0
}
>
  

        11.2 新增其他索引

> db.LABELNET.ensureIndex({"name":1,"age":1});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>

       11.3 檢視所有索引

> db.LABELNET.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "student.LABELNET"
        },
        {
                "v" : 1,
                "key" : {
                        "name" : 1,
                        "age" : 1
                },
                "name" : "name_1_age_1",
                "ns" : "student.LABELNET"
        }
]



       11.4 刪除索引

                可能隨著業務需求的變化,原先建立的索引可能沒有存在的必要了,可能有的人想說沒必要就沒必要唄,                但是請記住,索引會降低CUD這三種操作的效能。

> db.LABELNET.dropIndex("name_1_age_1");
{ "nIndexesWas" : 2, "ok" : 1 }
> db.LABELNET.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "student.LABELNET"
        }
]
>


   基本命令 就學到這裡了,下篇將學習使用 mongodb 的 C#驅動 實現增刪改查!