MongoDB—— 讀操作 Core MongoDB Operations (CRUD)


本文主要介紹內容:從MongoDB中請求數據的不同的方法

Note:All of the examples in this document use the mongo shell interface. All of these operations are available in an idiomatic interface for each language by way of theMongoDB Driver. See your driver documentation for full API documentation.

 

Queries in MongoDB 查詢

 find()

主要有find()和findOne()兩種查詢的方法,find()具體語法如下:

  db.collection.find( <query>, <projection> )

All queries in MongoDB address a single collection. 所有查詢操作都在一個集合中進行。
ps:可以在數據庫打開後,鍵入db指令,查看當前的數據庫;鍵入show collections 查看所有的集合。

其中<query>限制查詢篩選條件,如果爲空,則返回所有的文檔(documents)。
<projection>限制返回的查詢結果的域。

findOne()
findOne()不同之處:返回值類型爲一個文檔而不是遊標(類似指針)。

具體語法如下:
db.collection.findOne( <query>, <projection> )


Query Document
下面看一些<query>的例子:

   db.inventory.find( { type: 'food', price: { $lt: 9.95 } }, { item: 1, qty: 1 } )
在inventory集合中,查找type爲food,price少於9.95的文檔,返回這些文檔的item和qty以及_id。該函數返回值類型爲遊標。
db.inventory.find({}) 查詢集合中的所有文檔,也能寫成edb.inventory.find()。
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )篩選集合中type值爲food或snacks的文檔。

db.inventory.find( { $or: [ { qty: { $gt: 100 } },
                            { price: { $lt: 9.95 } } ]
                   } )篩選qty大於100或者price小於9.95的記錄。
同一個域中的“或” 使用$in表示,不同域之間的“或”使用$or表示。

篩選子文檔:
db.inventory.find( {
                     producer: {
                                 company: 'ABC123',
                                 address: '123 Street'
                               }
                   }
                 )
上面的例子可以使用點符號簡化,如下:
db.inventory.find( { 'producer.company': 'ABC123' } )

篩選第一個子文檔by域爲shipping的所有的文檔
db.inventory.find( { 'memos.0.by': 'shipping' } )

篩選至少有一個子文檔by域爲shipping的所有的文檔
db.inventory.find( { 'memos.by': 'shipping' } )


Result Projections
下面看一些<projection>的例子:

結果包含item和qty域以及默認的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

排除結果中默認的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )
 

高級查詢的補充知識:
摘自http://www.cnblogs.com/zhy4606/archive/2011/09/13/2175220.html
$all 匹配所有

這個操作符跟SQL語法的in類似,但不同的是, in只需滿足( )內的某一個值即可,  而$all必須滿足[ ]內的所有值,例如:
db.users.find({age : {$all : [6, 8]}});  
可以查詢出  {name: 'David', age: 26, age: [ 6, 8, 9 ] }  
但查詢不出  {name: 'David', age: 26, age: [ 6, 7, 9 ] }

$exists 判斷字段是否存在

查詢所有存在age字段的記錄  
db.users.find({age: {$exists: true}});  
查詢所有不存在name字段的記錄  
db.users.find({name: {$exists: false}});
 
Null 值處理

> db.c2.find({age:null})  

$mod 取模運算

查詢age取模6等於1的數據
db.c1.find({age: {$mod : [ 6 , 1 ] } })


$ne 不等於
查詢x的值不等於3 的數據
db.c1.find( { age : { $ne : 7 } } );


$in 包含
db.c1.find({age:{$in: [7,8]}});
 
$nin 不包含
查詢age的值在7,8 範圍外的數據 
db.c1.find({age:{$nin: [7,8]}});


$size 數組元素個數
對於{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }記錄
匹配db.users.find({favorite_number: {$size: 3}});
不匹配db.users.find({favorite_number: {$size: 2}});


 
正則表達式匹配

查詢name 不以T開頭的數據
db.c1.find({name: {$not: /^T.*/}});  


Javascript 查詢和$Where查詢
查詢a大於3的數據,下面的查詢方法殊途同歸
db.c1.find( { a : { $gt: 3 } } );
db.c1.find( { $where: "this.a > 3" } );
db.c1.find("this.a > 3");
f = function() { return this.a > 3; } db.c1.find(f); 
 

count 查詢記錄條數
db.users.find().count();
以下返回的不是5,而是user 表中所有的記錄數量
db.users.find().skip(10).limit(5).count();
如果要返回限制之後的記錄數量,要使用count(true)或者count(非0)
db.users.find().skip(10).limit(5).count(true);  


skip限制返回記錄的起點
從第3 條記錄開始,返回5 條記錄(limit 3, 5)
db.users.find().skip(3).limit(5);


Indexes索引

使用db.collection.ensureIndex()方法創建索引。
db.collection.ensureIndex( { <field1>: <order>, <field2>: <order>, ... } )

其中order選項,1表示升序,-1表示降序

The explain() cursor method allows you to inspect the operation of the query system, and is useful for analyzing the efficiency of queries, and for determining how the query uses the index.

db.inventory.find( { type: 'food' } ).explain()

可以通過查看描述,分析建立索引前後查詢效率的變化。MongoDB使用B樹建立索引。

Cursors遊標

範例:
var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;

if (myDocument) {
    var myItem = myDocument.item;
    printjson(myItem);
}

或者使用javascript語法:
var myCursor =  db.inventory.find( { type: 'food' } );

myCursor.forEach(printjson);

遊標在10分鐘後會自動回收,如果想要去除時間限制,設置如下:
var myCursor = db.inventory.find().addOption(DBQuery.Option.noTimeout);

Cursor Flags

mongo shell提供了以下cursor flags:

    DBQuery.Option.tailable
    DBQuery.Option.slaveOk
    DBQuery.Option.oplogReplay
    DBQuery.Option.noTimeout
    DBQuery.Option.awaitData
    DBQuery.Option.exhaust
    DBQuery.Option.partial


集合操作(aggregation)

包括以下四種:
    count (count())
    distinct (db.collection.distinct())
    group (db.collection.group())
    mapReduce. (Also consider mapReduce() and Map-Reduce.)

從Sharded Clusters中讀取數據

從Replica Sets中讀取數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章