3.2逻辑选择器
1.$or: 在一个数组上(二个或更多)执行逻辑||, 满足至少一个, 就算是满足2.$and: 逻辑 &&3.$not: 指定字段不匹配操作表达式, 或不存在该字段4.$nor:$not与$or结合体
3.2.1 $or
语法
{ $or: [ { }, { }, ... , { } ] }
> db.test1.find({"$or": [{"age":18}, {"name":"zhangsan"}]}) #满足{"name":"zhangsan"}, 输出 {"_id":ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} #满足{"age":18}, 输出 {"_id":ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }
$or与$in的异同
3.2.2$and
{ $and: [ { }, { } , ... , { } ] }
#没有满足的 > db.test1.find({"$and": [{"age":18}, {"name":"zhangsan"}]}) #同时满足全部条件:1.{"age":18}2.{"name":"xiaoming"} > db.test1.find({"$and": [{"age":18}, {"name":"xiaoming"}]}) {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }
3.2.3$not
{field: { $not: { } } }
执行$not
> db.test1.find({"age": {"$not":{"$gt":19}}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] } {"_id": ObjectId("58c9e4b80c4d4cf6f4563b26"),"name":"xiaohong"}
{"age": {"$not":{"$gt": 19}}}筛选的数据:
1.小于等于19;
2.不存在age字段段
3.2.4. $nor
{ $nor: [ { }, { }, ... { } ] }
> db.test1.find().pretty() {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_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"}
执行$nor
> db.test1.find({"$nor": [{"age": {"$gt":20}}, {"qty":10}]}) {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] } {"_id": ObjectId("58c9e4b80c4d4cf6f4563b26"),"name":"xiaohong"}
分解上述执行过程
1.age小于等于20, qty不等于10;2.age小于等于20, qty字段不存在;3.age字段不存在, qty不等于10;4.age字段不存在, qty字段不存在;
Tip
1.db.collection.count(): 集合内对象个数; 2.db.collection.dataSize(): 集合所占大小;