1. 程式人生 > 實用技巧 >MongoDB基礎知識

MongoDB基礎知識

一.文件

文件是MongoDB的核心概念。文件就是鍵值對的一個有序集。注意:鍵是唯一的

如下:

{
    "title":"test1",
    "content":"There is study",
    "date": new Date()
    }

  

二.集合

一組文件,相當與一張表,是動態模式

三.資料庫

多個集合可以組成資料庫

四.MongoDB shell簡介

MongoDB 自帶JavaScript shell,可在shell中使用命令列與MongoDB例項互動

shell中的基本操作

a.建立

insert

> post = {

... "title":"test1",

... "content":"There is study",

... "date": new Date()

... }

{

"title" : "test1",

"content" : "There is study",

"date" : ISODate("2020-07-28T05:49:53.951Z")

}

> db.blog.insert(post)

WriteResult({ "nInserted" : 1 })

b.讀取

find

> db.blog.find()

{ "_id" : ObjectId("5f1f8fc39da18cf3e2cf8071"), "title" : "test1", "content" : "There is study", "date" : ISODate("2020-07-28T02:38:59.968Z"), "width" : 3 }

{ "_id" : ObjectId("5f1fb9909da18cf3e2cf8072"), "title" : "test2", "content" : "There is study", "date" : ISODate("2020-07-28T05:37:20.426Z") }

{ "_id" : ObjectId("5f1fba699da18cf3e2cf8073"), "title" : "test3", "content" : "There is study", "date" : ISODate("2020-07-28T05:40:57.366Z"), "study" : [ "english", "chinese" ] }

{ "_id" : ObjectId("5f1fbaf49da18cf3e2cf8074"), "title" : "test4", "content" : "There is study", "date" : ISODate("2020-07-28T05:43:16.673Z"), "study" : [ "english", "chinese" ], "lickly" : { "food" : "mifan", "ball" : "football" } }

{ "_id" : ObjectId("5f1fbca0837f599809534b75"), "title" : "test1", "content" : "There is study", "date" : ISODate("2020-07-28T05:49:53.951Z") }

findOne


> db.blog.findOne()


{


"_id" : ObjectId("5f1f8fc39da18cf3e2cf8071"),


"title" : "test1",


"content" : "There is study",


"date" : ISODate("2020-07-28T02:38:59.968Z"),


"width" : 3


}

c.更新

update,至少有兩個引數:第一個是限定條件(用於匹配待更新的文件),第二個是新的文件

> post.conments = []

[ ]

> db.blog.update({"title":"test1"},post)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.blog.find({"title":"test1"})

{ "_id" : ObjectId("5f1f8fc39da18cf3e2cf8071"), "title" : "test1", "content" : "There is study", "date" : ISODate("2020-07-28T05:49:53.951Z"), "conments" : [ ] }

d.刪除

remove

> db.blog.remove({"title":"test1"})

五.資料型別

1.基本資料型別

.null

null用於表示空值或者不存在的欄位

"conmments" : null

.布林型

ture、false

.數值

"width" : 12.4
height:NumberInt(3)

.字串

"title" : "test1"

.日期

"date" : new Date()

.正則表示式

{"title":/test/}

.陣列

    "study" : [ 
        "english", 
        "chinese"
    ]

.內嵌文件

    "lickly" : {
        "food" : "mifan",
        "ball" : "football"
    }

.物件id

"_id" : ObjectId("5f1fb9909da18cf3e2cf8072")