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/>'; }