条件操作符用于比较两个表达式并从 mongoDB 集合中获取数据。
比较操作符
| 操作符 | 描述 | 示例 |
|---|
$eq | 等于 | { 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] } } |
查找点赞数大于1000且articleid为100001的文档
articledb> db.comment.find({articleid:"100001",likenum:{$gt:1000}})
[
{
_id: '5',
articleid: '100001',
content: '非常同意您的观点,健康才是最重要的财富。每天喝足量的水对于维持良好的身体状态至关重要。',
userid: '1006',
nickname: '月下独酌',
createdatetime: ISODate('2019-03-14T14:15:25.345Z'),
likenum: 1100,
state: '1'
},
{
_id: '6',
articleid: '100001',
content: '简单的幸福往往最珍贵。让我们从今天开始减少不必要的开支,并更加注重个人及家人的健康吧!',
userid: '1007',
nickname: '星梦奇缘',
createdatetime: ISODate('2019-12-25T00:00:00.000Z'),
likenum: 1200,
state: '1'
},
{
_id: '7',
articleid: '100001',
content: '今天,我想和大家分享一下关于健康饮食的问题。',
userid: '1008',
nickname: '风华浪尖',
createdatetime: ISODate('2019-05-05T10:30:15.123Z'),
likenum: 1300,
state: '1'
}
]
articledb>
逻辑操作符
| 操作符 | 描述 | 示例 |
|---|
$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" } ] } |
查找点赞数大于1200或昵称为 花开半夏 的文档:
articledb> db.comment.find({$or:[{likenum:{$gt:1200}},{nickname:"花开半夏"}]})
[ { _id: '4', articleid: '100001', content: '说得好!我们应该更加重视日常的小确幸,比如一杯干净温暖的水,它能给予我们无限的能量。', userid: '1005', nickname: '花开半夏', createdatetime: ISODate('2019-11-11T07:30:15.987Z'), likenum: 920, state: '1' }, { _id: '7', articleid: '100001', content: '今天,我想和大家分享一下关于健康饮食的问题。', userid: '1008', nickname: '风华浪尖', createdatetime: ISODate('2019-05-05T10:30:15.123Z'), likenum: 1300, state: '1' }]
articledb>
元素操作符
| 操作符 | 描述 | 示例 |
|---|
$exists | 字段是否存在 | { age: { $exists: true } } |
$type | 字段的 BSON 类型 | { age: { $type: "int" } } |
数组操作符
| 操作符 | 描述 | 示例 |
|---|
$all | 数组包含所有指定的元素 | { tags: { $all: ["red", "blue"] } } |
$elemMatch | 数组中的元素匹配指定条件 | { results: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } } |
$size | 数组的长度等于指定值 | { tags: { $size: 3 } } |
其他操作符
| 操作符 | 描述 | 示例 |
|---|
$regex | 匹配正则表达式 | { name: { $regex: /^A/ } } |
$text | 进行文本搜索 | { $text: { $search: "coffee" } } |
$where | 使用 JavaScript 表达式进行条件过滤 | { $where: "this.age > 25" } |