文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
find 的多条件查询
$in 修饰符
$in
修饰符可以轻松解决一键多值的查询情况。和 $in
相对的修饰符是 $nin
,即查询除了 $in
条件以外的值。
// 查询年龄是 10 或者 13 的学生
> db.student.find(
age: {$in:[10, 13]}},
{name:1, age:1, _id:0}
)
{ "name" : "lisi", "age" : 10 }
{ "name" : "xiaohong", "age" : 13 }
$nin
:
> db.student.find( {age: {$nin:[10,13]}},{name:1,age:1,_id:0} )
{ "name" : "wangwu", "age" : 12 }
{ "name" : "xiaohua", "age" : 12 }
{ "name" : "zhaoliu", "age" : 12 }
{ "name" : "xiaoli", "age" : 12 }
{ "name" : "xiaoliu", "age" : 12 }
{ "name" : "zhangsan", "age" : 12 }
{ "name" : "lihua", "age" : 12 }
{ "name" : "xiaozhang", "age" : 12 }
$or 修饰符
$or
修饰符用来查询多个键值的情况,就比如查询学生中大于等于 13 岁或者 hobbyOne 是篮球,而 $in
修饰符是用于一个 Key 值的情况,相对应的还有 $nor
修饰符。
> db.student.find( {$or: [ {age: {$gte: 13}}, {"hobby.hobbyOne": "篮球"} ]}, {name:1,hobby:1,age:1,_id:0} )
{ "name" : "lisi", "age" : 10, "hobby" : { "hobbyOne" : "篮球", "hobbyTwo" : "足球", "hobbyThree" : "羽毛球" } }
{ "name" : "xiaohong", "age" : 13, "hobby" : { "hobbyOne" : "瑜伽", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
{ "name" : "lihua", "age" : 12, "hobby" : { "hobbyOne" : "篮球", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
$nor
:
// 筛选年龄小于 13 且 hobbyOne 不是篮球的学生
> db.student.find( {$nor: [ {age: {$gte: 13}}, {"hobby.hobbyOne": "篮球"} ]}, {name:1,hobby:1,age:1,_id:0} )
{ "name" : "wangwu", "age" : 12, "hobby" : { "hobbyOne" : "游泳", "hobbyTwo" : "健身", "hobbyThree" : "乒乓球" } }
{ "name" : "xiaohua", "age" : 12, "hobby" : { "hobbyOne" : "体操", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
{ "name" : "zhaoliu", "age" : 12, "hobby" : { "hobbyOne" : "音乐", "hobbyTwo" : "美术", "hobbyThree" : "书法" } }
{ "name" : "xiaoli", "age" : 12, "hobby" : { "hobbyOne" : "体操", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
{ "name" : "xiaoliu", "age" : 12, "hobby" : { "hobbyOne" : "钓鱼", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
{ "name" : "zhangsan", "age" : 12, "hobby" : { "hobbyOne" : "足球", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
{ "name" : "xiaozhang", "age" : 12, "hobby" : { "hobbyOne" : "乒乓球", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
$and 修饰符
$and
用来查找几个 key 值都满足的情况。
// 筛选年龄大于等于 13 且 hobbyOne 是篮球的学生
> db.student.find( {$and: [ {age: {$gte: 13}}, {"hobby.hobbyOne": "瑜伽"} ]}, {name:1,hobby:1,age:1,_id:0} )
{ "name" : "xiaohong", "age" : 13, "hobby" : { "hobbyOne" : "瑜伽", "hobbyTwo" : "跳舞", "hobbyThree" : "书法" } }
$not 修饰符
$not
修饰符用来查询除条件之外的值。
// 查询除了大于等于 11,小于等于 12 的学生,即查询小于 11 或者大于 12 的学生
> db.student.find({
... age:{
... $not:{
... $lte:12,
... $gte:11
... }}},
... {name:1,age:1,_id:0})
{ "name" : "lisi", "age" : 10 }
{ "name" : "xiaohong", "age" : 13 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论