MongoDB :第七章:總結(jié)一下學(xué)習(xí)MongoDB的心得

創(chuàng)建了數(shù)據(jù)庫(kù) runoob:

> use runoob
switched to db runoob
> db
runoob
>
查看所有數(shù)據(jù)庫(kù)

    > show dbs
    admin   0.000GB
    local   0.000GB
    >

    注意: MongoDB 中默認(rèn)的數(shù)據(jù)庫(kù)為 test,如果你沒(méi)有創(chuàng)建新的數(shù)據(jù)庫(kù),集合將存放在 test 數(shù)據(jù)庫(kù)中。在 MongoDB 中,集合只有在內(nèi)容插入后才會(huì)創(chuàng)建! 就是說(shuō),創(chuàng)建集合(數(shù)據(jù)表)后要再插入一個(gè)文檔(記錄),集合才會(huì)真正創(chuàng)建。

創(chuàng)建的數(shù)據(jù)庫(kù) runoob 并不在數(shù)據(jù)庫(kù)的列表中, 要顯示它,我們需要向 runoob 數(shù)據(jù)庫(kù)插入一些數(shù)據(jù)。

    > db.runoob.insert({"name":"java小丑"})
    WriteResult({ "nInserted" : 1 })
    > show dbs
    local   0.078GB
    runoob  0.078GB
    test    0.078GB
    >

執(zhí)行刪除數(shù)據(jù)庫(kù) runoob:

先切換到數(shù)據(jù)庫(kù) runoob:

    > use runoob
    switched to db runoob
    >

再執(zhí)行刪除命令:

    > db.dropDatabase()
    { "dropped" : "runoob", "ok" : 1 }

創(chuàng)建簡(jiǎn)單集合mycol

先切換到數(shù)據(jù)庫(kù) runoob:

    > use runoob
    switched to db test
     
    再執(zhí)行創(chuàng)建site集合命令
    > db.createCollection("site")
    { "ok" : 1 }
    >

創(chuàng)建固定mycol集合 (表),整個(gè)集合空間大小 6142800 KB, 文檔最大個(gè)數(shù)為 10000 個(gè)。

    > db.createCollection("mycol", { capped : true, autoIndexId : true, size :
       6142800, max : 10000 } )
    { "ok" : 1 }
    >

capped : true固定集合是指有著固定大小的集合,當(dāng)達(dá)到最大值時(shí),它會(huì)自動(dòng)覆蓋最早的文檔。當(dāng)該值為 true 時(shí),必須指定 size 參數(shù)。

autoIndexId : true為 true,自動(dòng)在 _id 字段創(chuàng)建索引。默認(rèn)為 false。
查看集合(表)

先切換到數(shù)據(jù)庫(kù) runoob:

> use runoob
switched to db runoob
再執(zhí)行查看命令:
> show tables
site

查看已有集合(表)

    > show collections
    site

刪除集合(表)

先切換到數(shù)據(jù)庫(kù) runoob:

    > use runoob
    switched to db runoob
    > show tables
    site
    再執(zhí)行刪除site集合命令
    > db.site.drop()
    true
    > show tables
    >

插入文檔(插入的一條數(shù)據(jù))

 insert() 或 save() 方法向集合中插入文檔
 insert() 方式
向col集合插入文檔(向col表中插入一條記錄)

    >db.col.insert({title: 'MongoDB',
        description: 'MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)',
        by: 'javawxid',
        url: 'http://www.javawxid.com.cn',
        tags: ['mongodb', 'database', 'NoSQL'],
        likes: 100
    })

col 是我們的集合名,如果該集合不在該數(shù)據(jù)庫(kù)中, MongoDB 會(huì)自動(dòng)創(chuàng)建該集合并插入文檔。
查看向col集合已插入文檔(向col表插入的一條記錄)

    > db.col.find()
    { "_id" : ObjectId("56064886ade2f21f36b03134"), "title" : "MongoDB", "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)", "by" : "javawxid", "url" : "http://www.javawxid.com.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
    >

將數(shù)據(jù)定義為一個(gè)變量,如下所示:

    > document=({title: 'MongoDB',
        description: 'MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)',
        by: 'java小丑',
        url: 'http://www.javawxid.com.cn',
        tags: ['mongodb', 'database', 'NoSQL'],
        likes: 100
    });

執(zhí)行后顯示結(jié)果如下:

{
        "title" : "MongoDB",
        "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
        "by" : "java小丑",
        "url" : "http://www.javawxid.com.cn",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
執(zhí)行插入操作:

    > db.col.insert(document)
    WriteResult({ "nInserted" : 1 })
    >

    向集合col插入單條數(shù)據(jù)(向col表中插入單條數(shù)據(jù))
     
    > var document = db.col.insertOne({"a": 3})
    > document
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("571a218011a82a1d94c02333")
    }
     
      向集合col插入多條數(shù)據(jù)(向col表中插入多條數(shù)據(jù))
    > var res = db.col.insertMany([{"b": 3}, {'c': 4}])
    > res
    {
            "acknowledged" : true,
            "insertedIds" : [
                    ObjectId("571a22a911a82a1d94c02337"),
                    ObjectId("571a22a911a82a1d94c02338")
            ]
    }

一次插入多條數(shù)據(jù)

    1、先創(chuàng)建數(shù)組
    2、將數(shù)據(jù)放在數(shù)組中
    3、一次 insert 到集合中

    >var arr = [];
    >for(var i=1 ; i<=20000 ; i++){
    >.. arr.push({num:i});
    >}
    >db.numbers.insert(arr);
    BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 20000,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
    })

通過(guò) update() 方法來(lái)更新標(biāo)題(title):

將標(biāo)題(title)由原來(lái)的 "MongoDB" 更新為了 "javawxid"。

    >db.col.update({'title':'MongoDB'},{$set:{'title':'javawxid'}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })   # 輸出信息
    > db.col.find().pretty()
    {
            "_id" : ObjectId("56064f89ade2f21f36b03136"),
            "title" : "javawxid",
            "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
            "by" : "java小丑",
            "url" : "http://www.javawxid.com.cn",
            "tags" : [
                    "mongodb",
                    "database",
                    "NoSQL"
            ],
            "likes" : 100
    }
    >

只會(huì)修改第一條發(fā)現(xiàn)的文檔,如果你要修改多條相同的文檔,則需要設(shè)置 multi 參數(shù)為 true。

>db.col.update({'title':'MongoDB'},{$set:{'title':'javawxid'}},{multi:true})

使用save()方法來(lái)更新

我們替換了 _id 為 56064f89ade2f21f36b03136 的文檔數(shù)據(jù):

    db.col.save({
        "_id" : ObjectId("56064f89ade2f21f36b03136"),
        "title" : "MongoDB",
        "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
        "by" : "Runoob",
        "url" : "http://www.runoob.com",
        "tags" : [
                "mongodb",
                "NoSQL"
        ],
        "likes" : 110
    })

替換成功后,我們可以通過(guò) find() 命令來(lái)查看替換后的數(shù)據(jù)

db.col.find().pretty()

刪除文檔

我們移除 title 為 'MongoDB 教程' 的文檔:

    >db.col.remove({'title':'MongoDB 教程'})
    WriteResult({ "nRemoved" : 2 })           # 刪除了兩條數(shù)據(jù)
    >db.col.find()
    ……                                        # 沒(méi)有數(shù)據(jù)、

remove() 方法 并不會(huì)真正釋放空間。

需要繼續(xù)執(zhí)行 db.repairDatabase() 來(lái)回收磁盤(pán)空間。

    > db.repairDatabase()
    或者
    > db.runCommand({ repairDatabase: 1 })

remove() 方法已經(jīng)過(guò)時(shí)了,現(xiàn)在官方推薦使用 deleteOne() 和 deleteMany() 方法。

如刪除集合下全部文檔:

db.col.deleteMany({})

刪除 title等于 MongoDB 教程 的全部文檔:

db.col.deleteMany({ title: "MongoDB 教程" })

刪除 title等于 MongoDB 教程 的一個(gè)文檔:

db.col.deleteOne( { title: "MongoDB 教程" } )

查詢文檔
 

 

AND 條件

MongoDB 的 find() 方法可以傳入多個(gè)鍵(key),每個(gè)鍵(key)以逗號(hào)隔開(kāi),即常規(guī) SQL 的 AND 條件。

通過(guò) by 和 title 鍵來(lái)查詢 Java小丑 中 MongoDB 教程 的數(shù)據(jù)

    > db.col.find({"by":"Java小丑", "title":"MongoDB 教程"}).pretty()
    {
            "_id" : ObjectId("56063f17ade2f21f36b03133"),
            "title" : "MongoDB 教程",
            "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
            "by" : "Java小丑",
            "url" : "http://www.Javawxid.com.cn",
            "tags" : [
                    "mongodb",
                    "database",
                    "NoSQL"
            ],
            "likes" : 100
    }

OR 條件

MongoDB OR 條件語(yǔ)句使用了關(guān)鍵字 $or

查詢鍵 by 值為 菜鳥(niǎo)教程 或鍵 title 值為 MongoDB 教程 的文檔。

    >db.col.find({$or:[{"by":"Java小丑"},{"title": "MongoDB 教程"}]}).pretty()
    {
            "_id" : ObjectId("56063f17ade2f21f36b03133"),
            "title" : "MongoDB 教程",
            "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
            "by" : "Java小丑",
            "url" : "http://www.Javawxid.com.cn",
            "tags" : [
                    "mongodb",
                    "database",
                    "NoSQL"
            ],
            "likes" : 100
    }
    >

AND 和 OR 聯(lián)合使用

    >db.col.find({"likes": {$gt:50}, $or: [{"by": "Java小丑"},{"title": "MongoDB 教程"}]}).pretty()
    {
            "_id" : ObjectId("56063f17ade2f21f36b03133"),
            "title" : "MongoDB 教程",
            "description" : "MongoDB 是一個(gè) Nosql 數(shù)據(jù)庫(kù)",
            "by" : "Java小丑",
            "url" : "http://www.Javawxid.com.cn",
            "tags" : [
                    "mongodb",
                    "database",
                    "NoSQL"
            ],
            "likes" : 100
    }

類似常規(guī) SQL 語(yǔ)句為: 'where likes>50 AND (by = 'Java小丑' OR title = 'MongoDB 教程')'