mongodb中的find(四)

时间:2022-11-16 08:59:50

1.find例子

(1).查询主键为32的商品
db.goods.find({good_id:32})
(2).不属于第3栏目的所有商品
db.goods.find({cat_id:{$ne:3}},{goods_id:1,cat_id:1,goods_name:1})
(3).本店价格高于3000元的商品
db.goods.find({shop_price:{$gt:3000}},{name:1,shop_price:1})
(4).本店价格低于或等于100元的商品
db.goods.find({shop_price:{$lte:100}},{name:1,shop_price:1})
(5).取出第4栏目或第11栏目的商品
db.goods.find({cat_id:{$in:[4,11]}},{name:1,shop_price:1})
(6).取出100<=价格<=500的商品
db.goods.find({$and:[{shop_price:{$gte:100}},{shop_price:{$lte:500}}]},{goods_name:1,shop_price:1})
(7).取出不属于第3栏目且不属于第11栏目的商品(andnin和$nor分别实现)
db.goods.find({$and:[{cat_id:{$ne:3}},{cat_id:{$ne:11}}]},{goods_name:1,cat_id:1})
db.goods.find({cat_id:{$nin:[3,11]}},{goods_name:1,cat_id:1})
db.goods.find({$nor:[{cat_id:3},{cat_id:11}]},{goods_name:1,cat_id:1})
(8).取出价格大于100且小于300,或者大于3000 且小于6000的商品
db.goods.find({$or:[{$and:[{shop_price:{$gt:100}},{shop_price:{$lt:300}}]},{$and:[{shop_price:{$gt:3000}},{shop_price:{$lt:6000}}]}]},{goods_name:1,shop_price:1})
(9).取出goods_if%5 == 0,即0,5,15.这样的商品
db.goods.find({goods_id:{$mod:[5,0]}},{goods_name:1,goods_id:1,shop_price:1})
(10).取出名字以"诺基亚"开头的商品
db.goods.find({goods_name:{$regex:/^诺基亚.*/}},{goods_name:1,shop_price:1})
(11).判断某个列是否存在
db.user.find({age:{$exists:1}})   

2.不推荐使用where

$where用它可以在查询中执行任意的javaScript,这样就能在查询中做任何事情,为了安全起见,应严格限制,不是非常必要时,一定要避免使用where查询,因为它们在速度上要比常规查询慢很多。每个文档都要从BSON转换成javaScript对象,然后通过where表达式来运行,而且where语句不能使用索引,所以只有在走投无路时才考虑where这种用法,先使用常规查询进行过滤,然后再使用$where语句,这样组合使用可以降低性能损失。

$where   #性能很差

例子:

db.goods.find({$where:"this.shop_price > 3000"},{goods_name:1,shop_price:1})