1. 數據類型
MongoDB支持許多數據類型。
字符串 - 這是用於存儲數據的最常用的數據類型。MongoDB中的字符串必須為UTF-8
。
整型 - 此類型用於存儲數值。 整數可以是32
位或64
位,具體取決於服務器。
布爾類型 - 此類型用於存儲布爾值(true
/ false
)值。
雙精度浮點數 - 此類型用於存儲浮點值。
最小/最大鍵 - 此類型用於將值與最小和最大BSON
元素進行比較。
數組 - 此類型用於將數組或列表或多個值存儲到一個鍵中。
時間戳 - ctimestamp
,當文檔被修改或添加時,可以方便地進行錄制。
對象 - 此數據類型用於嵌入式文檔。
對象 - 此數據類型用於嵌入式文檔。
Null - 此類型用於存儲Null
值。
符號 - 該數據類型與字符串相同; 但是,通常保留用於使用特定符號類型的語言。
日期 - 此數據類型用於以UNIX時間格式存儲當前日期或時間。您可以通過創建日期對象並將日,月,年的日期進行指定自己需要的日期時間。
對象ID - 此數據類型用於存儲文檔的ID。
二進制數據 - 此數據類型用於存儲二進制數據。
代碼 - 此數據類型用於將JavaScript代碼存儲到文檔中。
正則表達式 - 此數據類型用於存儲正則表達式。
2. 插入文檔
2.1 insert()和save方法插入文檔
引導數據插入到MongoDB集合中,需要使用MongoDB的insert()或save()方法。
語法:
>db.COLLECTION_NAME.insert(document)
例子:
>db.mycol.insert({ _id: 100, title: 'MongoDB Overview', description: 'MongoDB is no sql database', by: 'yiibai tutorials', url: 'http://www.yiibai.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100, })
這里 mycol的英文集合的名稱,是在前一章創建的。如果數據庫中不存在集合,則MongoDB將創建此集合,然后將文檔插入到該集合中。
- 一個 4 字節的值,表示自 Unix 紀元以來的秒數
- 一個 3 字節的機器標識符
- 一個 2 字節的進程 ID
- 一個 3 字節的計數器,以隨機值開始
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
要在單個查詢中插入多個文檔,可以在insert()命令中傳遞文檔數組。如下所示:
> db.mycol.insert([ { _id: 101, title: 'MongoDB Guide', description: 'MongoDB is no sql database', by: 'xhh tutorials', url: 'http://www.baidu.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 }, { _id: 102, title: 'NoSQL Database', description: "NoSQL database doesn't have tables", by: 'xhh tutorials', url: 'http://www.baidu.com', tags: ['mongodb', 'database', 'NoSQL'], likes: 210, comments: [ { user:'user1', message: 'My first comment', dateCreated: new Date(2017,11,10,2,35), like: 0 } ] }, { _id: 104, title: 'Python Quick Guide', description: "Python Quick start ", by: 'xhh tutorials', url: 'http://www.baidu.com', tags: ['Python', 'database', 'NoSQL'], likes: 30, comments: [ { user:'user1', message: 'My first comment', dateCreated: new Date(2018,11,10,2,35), like: 590 } ] } ])
2.2 其他插入文檔的方法
2.2.1 db.collection.insertOne()方法
如果將文檔_id分配給MongoDB,會自動將_id與其ObjectId值添加到新文檔。
db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )
方法返回包含新插入的文檔的_id細分值的文檔。
> db.inventory.insertOne( ... { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5955220846be576f199feb55") } >
2.2.2 db.collection.insertMany()方法
db.inventory.insertMany([ { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ])
方法返回包含新插入的文檔的_id細分值的文檔。
> db.inventory.insertMany([ ... { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, ... { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }, ... { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } } ... ]) { "acknowledged" : true, "insertedIds" : [ ObjectId("59552c1c46be576f199feb56"), ObjectId("59552c1c46be576f199feb57"), ObjectId("59552c1c46be576f199feb58") ] } >
3. 查詢文檔
3.1 find()方法
要從MongoDB集合查詢數據,需要使用MongoDB的find()方法。
語法:
>db.COLLECTION_NAME.find(document)
方法將以非結構化的方式顯示所有文檔。
3.2 pretty()方法
> db.mycol.find().pretty()
例子:
>db.mycol.find().pretty() { "_id": 100, "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "yiibai tutorials", "url": "http://www.yiibai.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
除了find()方法外,還有一個findOne()方法,它只返回一個文檔。
3.3 MongoDB與RDBMS的等效Where子句
要在一些條件的基礎上查詢文檔,可以使用以下操作。
操作 | 語法 | 示例 | RDBMS等效語句 |
---|---|---|---|
相等 | {<key>:<value>} |
db.mycol.find({"by":"yiibai"}).pretty() |
where by = 'yiibai' |
小於 | {<key>:{$lt:<value>}} |
db.mycol.find({"likes":{$lt:50}}).pretty() |
where likes < 50 |
小於等於 | {<key>:{$lte:<value>}} |
db.mycol.find({"likes":{$lte:50}}).pretty() |
where likes <= 50 |
大於 | {<key>:{$gt:<value>}} |
db.mycol.find({"likes":{$gt:50}}).pretty() |
where likes > 50 |
大於等於 | {<key>:{$gte:<value>}} |
db.mycol.find({"likes":{$gte:50}}).pretty() |
where likes >= 50 |
不等於 | {<key>:{$ne:<value>}} |
db.mycol.find({"likes":{$ne:50}}).pretty() |
where likes != 50 |
3.4 MongoDB中的AND操作符
語法:
在find()方法中,如果通過‘,’將它們分開傳遞多個鍵,則MongoDB將其視為AND條件。
>db.mycol.find( { $and: [ {key1: value1}, {key2:value2} ] } ).pretty()
例子:
以下示例將顯示由“xhh tutorials”編寫並且標題為“MongoDB Overview”的所有教程。
> db.mycol.find({$and:[{"by":"xhh tutorials"},{"title": "MongoDB Overview"}]}).pretty() { "_id" : 100, "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "yiibai tutorials", "url" : "https://www.cnblogs.com/liuhui0308/", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
對於上面給出的例子,等效的SQL where子句是:
SELECT * FROM mycol where by ='yiibai tutorials' AND title ='MongoDB Overview'
可以在find子句中傳遞任意數量的鍵值。
35 MongoDB中的OR操作符
>db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
例子:
以下示例將顯示由“xhh tutorials”編寫並且標題為“MongoDB Overview”的所有教程。
>db.mycol.find({$or:[{"by":"xhh tutorials"},{"title": "MongoDB Overview"}]}).pretty() { "_id": 100, "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "yiibai tutorials", "url": "https://www.cnblogs.com/liuhui0308/",
"tags": [
"mongodb",
"database",
"NoSQL"
],
"likes": "100"
}
>
3.6 AND和OR聯合使用
10
以及標題是“MongoDB”或者“xhh tutorials”的所有文檔。
SELECT * FROM mycol where likes> 10 AND(by ='yiibai tutorials' OR title ='MongoDB Overview')
代碼:
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "yiibai tutorials"}, {"title": "MongoDB Overview"}]}).pretty() { "_id": 100, "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "yiibai tutorials", "url": "http://www.yiibai.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
3.7 查詢嵌入/嵌套文檔
數據准備:
db.inventory.insertMany( [ { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }, { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }, { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }, { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }, { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" } ]);
3.4.1 匹配嵌入/嵌套文檔
要在作為嵌入/嵌套文檔的字段上指定相等條件,請使用查詢過濾器文檔{<field>:<value>},其中<value>是要匹配的文檔。
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
整個嵌入式文檔中的相等匹配需要精確匹配指定的<value>文檔,包括字段順序。
例如,以下查詢與庫存(inventory)集合中的任何文檔不匹配:
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } }
3.4.2 查詢嵌套字段
要在嵌入/嵌套文檔中的字段上指定查詢條件,請使用點符號(“field.nestedField
”)。在嵌套字段上指定等於匹配。
db.inventory.find( { "size.uom": "in" } )
3.4.3 使用查詢運算符指定匹配
{ <field1>: { <operator1>: <value1> }, ... }
以下查詢使用size字段中嵌入的字段h中的小於運算符($lt):
db.inventory.find( { "size.h": { $lt: 15 } } )
3.4.4 指定AND條件
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )