MongoDB 中的關係運算符,邏輯運算符,數組條件,內嵌文檔,正則過濾,正、倒序排序,限定數量 ...
1. 關係運算符
$eq 等於
$lt 小於
$lte 小於等於
$gt 大於
$gte 大於等於
$in 在範圍內
//查詢名字為“小明”和“小剛”的 $condition = [ 'name' => ['$in' => ['小明','小剛']] ]; $result = $collection -> find($condition,['_id'=>false]);
2. 邏輯運算符
$and 並且(預設的邏輯關係就是並且)
//查詢名年齡大於10並小於30的 $condition = [ '$and' => [ ['age' => ['$gt' => 10]], ['age' => ['$lt' => 30]] ] ]; $result = $collection -> find($condition,['_id'=>false]);
$and 簡寫方式:
//查詢名年齡大於10並小於30的 $condition = [ 'age' => ['$gt' => 10,'$lt' => 30] ]; $result = $collection -> find($condition,['_id'=>false]);
$or 或者
//查詢名年齡等於10或等於30的 $condition = [ '$or' => [ ['age' => ['$eq' => 10]], ['age' => ['$eq' => 30]] ] ]; $result = $collection -> find($condition,['_id'=>false]);
$not 非
//查詢名年齡不等於10的 $condition = [ 'age' => ['$not' => ['$eq' => 10]] ]; $result = $collection -> find($condition,['_id'=>false]);
3. 數組條件
- 當屬性的值是數組時,查詢需特殊處理
- 查詢條件中,屬性的值是字元串,表示查找的條件中包含該字元串
//查詢hobby里包含swim的 $condition = [ 'hobby' => 'swim' ]; $result = $collection -> find($condition,['_id'=>false]);
-
- 查詢條件中,屬性的值包含多個內容,使用$all連接
//查詢hobby里包含swim和climb的 $condition = [ 'hobby' => ['$all' => ['swim','climb']] ]; $result = $collection -> find($condition,['_id'=>false]);
-
- 查詢條件中,屬性的值是一個數組,表示嚴格等於數組的元素
//查詢hobby里就是swim和climb的 $condition = [ 'hobby' => ['swim','climb'] ]; $result = $collection -> find($condition,['_id'=>false]);
4. 內嵌文檔
內嵌文檔的表現形式類似於屬性的值又是一個文檔
例如:{
"name":"小明",
"score":{
"Math":100,
"Chinese”:90
}
}
- 通過 . 點號 獲得內嵌文檔的屬性值
//查詢數學分數大於80的 $condition = [ 'score.math' => ['$gt' => 80] ]; $result = $collection -> find($condition,['_id'=>false]);
5. 正則過濾
使用正則表達式進行過濾
//查詢名字以“小”開頭的 $condition = [ 'name' => new MongoRegex('/^小/') ]; $result = $collection -> find($condition,['_id'=>false]);
6. 排序
註:需要先查詢,再對查詢的結果進行排序
通過查詢結果(cursor游標)的sort方法進行排序,排序有2種方式:
-
- 1 正序
- -1 倒序
//查詢結果 $cursor = $collection -> find([],['_id'=>false]); //對查詢結果倒序排序 $result = $cursor -> sort(['score.math'=>-1]); foreach($result as $key => $value){ echo ($value['name'].':'.$value['score']['math']).'<br/>'; }
7. 限定數量
對查詢的結果進行限定,該方法屬於cursor游標的
-
- skip() 忽略多少
- limit() 保留多少
//查詢結果 $cursor = $collection -> find([],['_id'=>false]); //對查詢結果倒序排序,忽略前三個,保留後兩個 $result = $cursor -> sort(['score.math'=>-1]) -> skip(3) -> limit(2); foreach($result as $key => $value){ echo ($value['name'].':'.$value['score']['math']).'<br/>'; }