MongoDB 查询文档(二)

第三部分查询选择器

3.1比较选择器

[eq:equal,g:greater,l:less,t:than,n:not,in:in]

1.$eq    :对比值等于指定值

2.$gt    :...大于...

3.$gte:...大于等于...

4.$lt:...大于...

5.$lte:...小于等于...

6.$ne    :对比值全部不等于指定值

7.$in:指定数组包含对比值

8.$nin:指定数组不包含对比值

3.1.1 $eq

配置键值对[两种写法]

#eq

db.test1.find({"age": {"$eq":18}})

{"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }

#省略, 结果一样

> db.test1.find({"age":18})

匹配数组元素

> db.test1.find({"score": {"$eq":80}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10}  #省略, 结果一样 > db.test1.find({"score":80})

匹配数组

#无结果, 因为在此是相当于 db.test1.find({"score": {"$eq": [20,30]}}) > db.test1.find({"score": [20,30]}) > db.test1.find({"score": [20,40]}) {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }

3.1.2 $gt除了数字可以比较之外,不能忽略BJSON其他类型都可以比较

数字

> db.test1.find({"age": {"$gt":20}}) {"_id": ObjectId("58c8dc54ef9b994487420f2a"),"name":"lisi","age":29,"score": [40,60] }

字符串同样可以比较更多参考BSON Types

> db.test1.find({"name": {"$gt":"lisi"}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }

3.1.3 $gte

> db.test1.find({"age": {"$gte":19}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_id": ObjectId("58c8dc54ef9b994487420f2a"),"name":"lisi","age":29,"score": [40,60] }

3.1.4. $lt

> db.test1.find({"age": {"$lt":19}}) {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }

3.1.5. $lte

> db.test1.find({"age": {"$lte":19}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_id": ObjectId("58c8dc54ef9b994487420f2b"),"name":"xiaoming","age":18,"score": [20,40] }

3.1.6 $ne不等于指定值

> db.test1.find({"name": {"$ne":"xiaoming"}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} {"_id": ObjectId("58c8dc54ef9b994487420f2a"),"name":"lisi","age":29,"score": [40,60] }

3.1.7 $in符合指定数组内的任一个即满足

> db.test1.find({"score": {"$in": [90,100]}}) {"_id": ObjectId("58c8dc54ef9b994487420f29"),"name":"zhangsan","age":19,"score": [90,80],"qty":10} > db.test1.find({"score": {"$in": [89,100]}})

3.1.8 $nin指定数据都不属于指定数组的子集

#三条数据全部不存在89100, 就输出 > db.test1.find({"score": {"$nin":[89, 100]}}) {"_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 ]}

你可能感兴趣的:(MongoDB 查询文档(二))