1. 条件操作符
在Mongodb中,条件插座福用于查询文档时进行过滤、比较和逻辑操作,这些操作符可以下几类:比较操作符、逻辑操作符、元素操作符、数组操作符、以及其他常用操作符
1.1 比较操作符
操作符 | 描述 | 示例 |
---|---|---|
$eg | 等于 | { age: { $eq: 25 } } |
$ne | 不等于 | { age: { $ne: 25 } } |
$gt | 大于 | { age: { $gt: 25 } } |
$gte | 大于等于 | { age: { $gte: 25 } } |
$lt | 小于 | { age: { $lt: 25 } } |
$lte | 小于等于 | { age: { $lte: 25 } } |
$in | 在指定的数组中 | { age: { $in: [25, 30, 35] } } |
$nin | 不在指定的数组中 | { age: { $nin: [25, 30, 35] } } |
1.2 逻辑操作符
操作符 | 描述 | 示例 |
---|---|---|
$and | 逻辑与,符合所有条件 | { $and: [ { age: { $gt: 25 } }, { city: “New York” } ] } |
$or | 逻辑或,符合任意条件 | { $or: [ { age: { $lt: 25 } }, { city: “New York” } ] } |
$not | 取反,不符合条件 | { age: { $not: { $gt: 25 } } } |
$nor | 逻辑或非,均不符合条件 | { $nor: [ { age: { $gt: 25 } }, { city: “New York” } ] } |
1.3 元素操作符
操作符 | 描述 | 示例 |
---|---|---|
$exists | 字段是否存在 | { age: { $exists: true } } |
$type | 字段的 BSON 类型 | { age: { $type: “int” } } |
1.4 数组操作符
操作符 | 描述 | 示例 |
---|---|---|
$all | 数组包含所有指定的元素 | { arrays: { $all: [“red”, “blue”] } } |
$elemMatch | 数组中的元素匹配指定条件 | { arrays: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } } |
$size | 数组的长度等于指定值 | { arrays: { $size: 3 } } |
1.5 其他操作符
操作符 | 描述 | 示例 | 解释 |
---|---|---|---|
$regex | 匹配正则表达式 | { name: { $regex: /^A/ } } | 查询name以A开头的 |
$text | 进行文本搜索 | { $text: { $search: “coffee” } } | 查询文档包含coffee |
$where | 使用 JavaScript 表达式进行条件过滤 | { $where: “this.age > 25” } | 查询年龄大于25 |
$near | 查找接近指定点的文档 | db.collection.find({ location: { $near: [10, 20], $maxDistance: 1000 } }) | 查询经度10纬度20,附近1000米的地点 |
$geoWithin | 查找在指定地理区域内的文档 | db.collection.find({ location: { $geoWithin: { $centerSphere: [[10, 20], 1] } } }) | 查找经度10纬度20区域内的文档 |
2. $type操作符
在 MongoDB 中,$type 操作符用于查询具有指定类型的字段的文档。 MongoDB 的 $type 操作符用于查询字段的 BSON 数据类型。 它允许您指定一个或多个类型,并返回匹配这些类型的文档。
1 | 语法: |
field:要检查类型的字段。
type:指定的 BSON 类型,可以是类型的数字代码或类型名称的字符串。
2.1 BSON类型
以下是常见的BSON类型及其对应的数字代码和字符串名称
类型代码 | 类型名称 |
---|---|
1 | double |
2 | string |
3 | object |
4 | array |
5 | binData |
6 | undefined |
7 | objectId |
8 | bool |
9 | date |
10 | null |
11 | regex |
12 | dbPointer |
13 | javascript |
14 | symbol |
15 | javascriptWithScope |
16 | int |
17 | timestamp |
18 | long |
19 | decimal |
127 | maxKey |
255 | minKey |
实例:
查询字段类型为字符串的文档
1
2
3
4db.myCollection.find({ fieldName: { $type: "string" } })
或者使用类型代码
db.myCollection.find({ fieldName: { $type: 2 } })查找字段类型为数字的文档,例如,查找 age 字段类型为整数的文档
1
db.myCollection.find({ fieldName: { $type: "string" } })
查询字段类型为字符串的文档
1
2
3
4db.myCollection.find({ age: { $type: "int" } })
或者
db.myCollection.find({ age: { $type: 16 } })查找字段类型为布尔值的文档
1
2
3
4db.myCollection.find({ isActive: { $type: "bool" } })
或者
db.myCollection.find({ isActive: { $type: 8 } })