本章节中,我们将讨论如何在 MongoDB 中使用条件操作符。条件操作符用于比较两个表达式并从 MongoDB 集合中获取数据。MongoDB 中条件操作符有:
(>) 大于 - $gt
(<) 小于 - $lt
(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte
向 col 集合插入六个文档,如下:
# 插入文档
test> db.col.insertMany([{name:"张三", age:18, email:"zhangsan@outlook.com"},
{name:"李四", age:22, email:"lisi@qq.com"},
{name:"王五", age:26, email:"wangwu@sina.com.cn"},
{name:"赵六", age:27, email:"zhaoliu@gmail.com"},
{name:"顾七", age:30, email:"guqi@qq.com"},
{name:"何八", age:42, email:"heba@outlook.com"}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64e71af810366fa87109a12f"),
'1': ObjectId("64e71af810366fa87109a130"),
'2': ObjectId("64e71af810366fa87109a131"),
'3': ObjectId("64e71af810366fa87109a132"),
'4': ObjectId("64e71af810366fa87109a133"),
'5': ObjectId("64e71af810366fa87109a134")
}
}
# 查询 col 集合所有文档
test> db.col.find()
[
{
_id: ObjectId("64e71af810366fa87109a12f"),
name: '张三',
age: 18,
email: 'zhangsan@outlook.com'
},
{
_id: ObjectId("64e71af810366fa87109a130"),
name: '李四',
age: 22,
email: 'lisi@qq.com'
},
{
_id: ObjectId("64e71af810366fa87109a131"),
name: '王五',
age: 26,
email: 'wangwu@sina.com.cn'
},
{
_id: ObjectId("64e71af810366fa87109a132"),
name: '赵六',
age: 27,
email: 'zhaoliu@gmail.com'
},
{
_id: ObjectId("64e71af810366fa87109a133"),
name: '顾七',
age: 30,
email: 'guqi@qq.com'
},
{
_id: ObjectId("64e71af810366fa87109a134"),
name: '何八',
age: 42,
email: 'heba@outlook.com'
}
]如果你想获取 col 集合中 age 大于 30 的数据,你可以使用以下命令:
test> db.col.find({ age:{$gt:30} })
[
{
_id: ObjectId("64e71af810366fa87109a134"),
name: '何八',
age: 42,
email: 'heba@outlook.com'
}
]类似于SQL语句:
Select * from col where age>30;
如果你想获取 col 集合中 age 大于等于 30 的数据,你可以使用以下命令:
test> db.col.find({ age:{$gte:30} })
[
{
_id: ObjectId("64e71af810366fa87109a133"),
name: '顾七',
age: 30,
email: 'guqi@qq.com'
},
{
_id: ObjectId("64e71af810366fa87109a134"),
name: '何八',
age: 42,
email: 'heba@outlook.com'
}
]类似于SQL语句:
Select * from col where age>=30;
如果你想获取 col 集合中 age 小于 22 的数据,你可以使用以下命令:
test> db.col.find({ age:{$lt:22} })
[
{
_id: ObjectId("64e71af810366fa87109a12f"),
name: '张三',
age: 18,
email: 'zhangsan@outlook.com'
}
]类似于SQL语句:
Select * from col where likes < 22;
如果你想获取 col 集合中 age 小于等于 22 的数据,你可以使用以下命令:
test> db.col.find({ age:{$lte:22} })
[
{
_id: ObjectId("64e71af810366fa87109a12f"),
name: '张三',
age: 18,
email: 'zhangsan@outlook.com'
},
{
_id: ObjectId("64e71af810366fa87109a130"),
name: '李四',
age: 22,
email: 'lisi@qq.com'
}
]类似于 SQL 语句:
Select * from col where age <= 22;
如果你想获取 col 集合中 age 大于等于 25,小于等于 30 的数据,你可以使用以下命令:
test> db.col.find({ age:{$gte:25, $lte:30} })
[
{
_id: ObjectId("64e71af810366fa87109a131"),
name: '王五',
age: 26,
email: 'wangwu@sina.com.cn'
},
{
_id: ObjectId("64e71af810366fa87109a132"),
name: '赵六',
age: 27,
email: 'zhaoliu@gmail.com'
},
{
_id: ObjectId("64e71af810366fa87109a133"),
name: '顾七',
age: 30,
email: 'guqi@qq.com'
}
]类似于 SQL 语句:
Select * from col where age>=25 AND age<=30;