如果数据库中尚未有数据, 准备测试数据
db.test1.insertMany([ {"name":"zhangsan","age":19,"score": [90,80]}, {"name":"lisi","age":29,"score": [40,60]}, {"name":"xiaoming","age":18,"score": [20,40]}, {"name":"xiaohong"} ])
第一部分元素操作符
1.$exists: 判断指定字段是否存在,并返回相应的结果2.$type: 匹配字段对应的类型
1.1$exists
{field: { $exists: } }
判断指定字段是否存在,并返回相应的结果, 直接上代码
{"$exists": true}
> db.test1.find({"qty": {"$exists":true}})#张三存在qty属性, 就返回该条数据{"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age": 19,"score": [ 90, 80 ],"qty": 10 }
{"$exists": false}
> db.test1.find({"qty": {"$exists":false}})#以下三条数据均不存在qty字段{"_id": ObjectId("58c8dc54ef9b994487420f2a"),"name":"lisi","age": 29,"score": [ 40, 60 ] } {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age": 18,"score": [ 20, 40 ] } {"_id": ObjectId("58c9e4b80c4d4cf6f4563b26"),"name":"xiaohong"}
1.2 $type
{field: { $type: | } }
第二部分
1.$mod模运算2.$regex 正则表达3.$text 文本搜索4.$where: 支持js表达式
2.1 $mod运算
db.users.find('this.age % 6 == 0'); 或者 > db.users.find({"age": {$mod : [6,0]}}); {"_id": ObjectId("58d21667edca14f0f7ffbedb"),"name":"xiaoming","age":18,"score": [20,40] }
2.2 $regex正则表达
注: 之后后专门整理一篇正则表达式的文章
2.3 $text
2.4 where