MongoDB與BSON

MongDB使用 BSON 存儲數據。

什麼是BSON

BSON 全稱Bin­ary JSON,MongoDB 把它轉化成一個概念叫文檔(Document)

MongoDB的數據類型與JS的對應

null

布爾

32位整數、64位整數、64位浮點數

對應 JS 的 number

字符串

對象

數組

undefined

日期

對應 JS 中的日期對象 new Date()

正則表達式

JS 中的正則表達式對象 /foo/i

函數

ObjectId

文檔必須有_id鍵,這個鍵可以是任何類型,默認是 ObjectId 對象。集合中_id必須唯一。

ObjectId 有 12 個字節,用十六進制數字表示,12*8/4=24個十六進制,前 4 個字節表示時間戳(秒),然後 3 個字節表示機器主機名的散列值,然後 2 個字節表示進程標識符PID,最後 3 字節表示自動增加的計數器

總結

可以看出,對於 JS 來講,MongoDB 中的 BSON 比 JSON(null、布爾、數字、字符串、對象、數組)多了undefined、日期、正則表達式、函數、ObjectId

測試

db.user.insert({
    a: null, 
    b: true, 
    c: 27,  
    d: 'hello',  
    e: {foo: 'hello'},  
    f: [1, 2, 3],  
    g: undefined,  
    h: new Date(),  
    i: /foo/i,  
    j: function () {},  
    k: ObjectId() 
})

> db.user.findOne({d: 'hello'})
{
    "_id" : ObjectId("587647e0f63a422562dc8ef1"),
    "a" : null,
    "b" : true,
    "c" : 27,
    "d" : "hello",
    "e" : {
        "foo" : "hello"
    },
    "f" : [
        1,
        2,
        3
    ],
    "g" : undefined,
    "h" : ISODate("2017-01-11T14:57:36.980Z"),
    "i" : /foo/i,
    "j" : function () {},
    "k" : ObjectId("587647e0f63a422562dc8ef0")
}

> var x = db.user.findOne()
> typeof x.a
object
> typeof x.b
boolean
> typeof x.c
number
> typeof x.d
string
> typeof x.e
object
> typeof x.f
object
> typeof x.g
undefined
> typeof x.h
object
> typeof x.i
object
> typeof x.j
function
> typeof x.k
object
發佈了237 篇原創文章 · 獲贊 91 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章