6/18/2013

Mongo Math

以下介紹一些常用到的指令
$gt: greater than 大於           $gte: greater than and equal to 大於等於      
$lt: less than       小於           $lte: greater than and equal to 小於等於

以下用到的練習的collection名稱為school (學校)
document(文檔)包括: department(系所),  professor(教授姓名), student(學生姓名),  field(研究領域), grade(年級), point(學分數)

Greater than 大於

在Mongo Shell裡可以用db.school.find ({ "point" : {$gt : 20} });
例如   搜尋學分數大於20的學生資料
下列練習可以發現command line將學分數為40, 33, 25, 36的紀錄都列出來


在Java中若要找學分數大於30的紀錄,可使用
DBCollection coll = db.getCollection("Collection Name");
DBObject query = 
new QueryBuilder().put("Document Name").greaterThan(Value).get();

DBCollection coll = db.getCollection("school");
DBObject query = new QueryBuilder().put("point").greaterThan(33).get();

Greater than and equal to 大於等於

在Mongo shell裡面使用 $gte,在Java則使用
DBObject query = 
new QueryBuilder().put("document name").greaterThanEquals(Value).get();
在Concole可以看到把學分數(point)為40, 33, 46的紀錄都列出來了


Less than 小於

類似Greater的語法  這裡假設找出學分數小於33的紀錄
使用DBObject query = 
new QueryBuilder().put("point").lessThan(33).get();


Less than and euqal to 小於等於

在Mongo shell可使用$lte,在Java則使用lessThanEquals(Value)
DBObject query = new QueryBuilder().put("point").lessThanEquals(33).get();
這個練習把學分數等於33的紀錄也列出來


下圖分別列出小於20跟大於20的練習


介於兩數值之間

若要查詢介於某個數值跟某個數值之間
例如大於20且小於40
則可用    db.school.find ({ "point" : {$gt : 20,  $lt:40} });