MongoDB查詢文檔使用find()方法,同時find()方法以非結構化的方式來顯示全部查詢到的文檔。web
-- 1.基本語法 db.collection.find(query, projection) -- 返回全部符合查詢條件的文檔 db.collection.findOne(query, projection) -- 返回第一個符合查詢條件的文檔 -- query:可選,查詢條件操做符,用於指定查詢條件 -- projection:可選,投影操做符,用來指定須要返回的鍵(默認省略) -- 例1:查詢users集合中年齡爲18的全部文檔 db.users.find({age: 18}) -- 2.若是須要以易讀的方式來觀察數據,能夠使用pretty()方法 db.collection.find(query, projection).pretty()
MongoDB的find()方法能夠傳入多個鍵,每一個鍵以逗號隔開,這樣便可起到SQL的AND條件正則表達式
-- 1.AND條件基本語法 db.collection.find({key1:value1, key2:value2}) -- 例1:查詢users集合中年齡爲18的女生的全部文檔 db.users.find({age: 18, sex: 'girl'}) -- 2.OR條件基本語法 db.collection.find({ $or: [ {key1: value1}, {key2:value2} ] }) -- 例2:查詢users集合中年齡爲18或性別爲女生的全部文檔 db.users.find({ $or: [ {age: 18}, {sex: 'girl'} ] })
條件操做符用處理條件關係以從MongoDB中查詢符合條件的文檔數據,條件操做符以下:sql
-- 查詢users集合中年齡大於18歲的文檔數據 db.users.find({age : {$gt : 18}}) -- 查詢users集合中年齡小於18歲的文檔數據 db.users.find({age : {$lt : 18}}) -- 查詢users集合中年齡大於等於18歲的文檔數據 db.users.find({age : {$gte : 18}}) -- 查詢users集合中年齡大於等於18歲的文檔數據 db.users.find({age : {$lte : 18}})
$type操做符是基於BSON類型來檢索集合中匹配的數據類型,MongoDB中能夠使用查詢的數據類型以下表:數組
類型 | $type表明數字 | 說明 |
---|---|---|
Double | 1 | 64位浮點數 |
String | 2 | 字符串類型 |
Object | 3 | 對象類型 |
Array | 4 | 數組類型 |
Binary Data | 5 | 二進制數據類型 |
Objectid | 7 | 對象id類型 |
Boolean | 8 | 布爾類型 |
Date | 9 | 日期類型 |
Null | 10 | 用於表示空值或不存在的字段 |
Regular Expression | 11 | 正則表達式類型 |
JavaScript | 13 | JavaScript代碼 |
JavaScript (with scope) | 15 | 帶做用域的JavaScript代碼 |
32-bit integer | 16 | 32位整數 |
Timestamp | 17 | 時間戳類型 |
64-bit integer | 18 | 64位整數 |
Min key | -1 | 最小鍵 |
Max key | 127 | 最大鍵 |
下面我將使用$type,做爲查詢條件舉例說明:code
-- 例:查詢users集合中,姓名爲字符串類型的文檔 db.users.find({"name" : {$type : 2}})
下面我將使用limit()與skip()方法舉例說明。對象
-- 使用語法(limit()、skip()、sort()方法能夠組合使用) db.collectionName.find().limit(NUMBER) db.collectionName.find().skip(NUMBER) db.collectionName.find().sort({"key": 1/-1}) -- 例1:跳過前50條數據查詢users集合中姓名字段爲字符串類型的100以內的數據 db.users.find({"name" : {$type : 2}}).limit(100).skip(50) -- 例2:將查詢到users集合中姓名字段爲字符串類型的文檔數據按升序排列 db.users.find({"name" : {$type : 2}}).sort({"name": 1})
這裏先介紹一下正則表達式:正則表達式是使用單個字符串來描述、匹配一系列符合某個句法規則的字符串。
MongoDB中使用$regex操做符來設置匹配字符串的正則表達式語言。排序
-- 使用語法 db.collectionName.find({key:{ $regex: regex, $options: options }}) -- 例:不區分大小寫查詢users集合中姓名包含web的文檔數據(如下兩種方式查詢結果相同) db.users.find({ "name" : { $regex : "web", $options: "i" } }) db.users.find({ "name" : /web/i } })