Markdown 笔记

忽略,限制和排序查询选项1
db.reviews.find({'product_id':product['_id']}).skip(0).limit(12).sort({'helpful_votes':-1})

1
1
db.reviews.find({'product_id':product['_id']}).skip(0).limit(12).sort({'helpful_votes':-1})

skip+limit实现分页。sort实现排序(降序)。

投影查询(相当于SQL中的select [指定字段] )
db.users.findOne( { 'username':'kbanker', 'hashed_password':'bd1cfa194c3a603e7186780824b04419'},{'_id':1})
{ "_id" : "4c4b1476238d3b4dd5000001" }

2
1
db.users.findOne( { 'username':'kbanker', 'hashed_password':'bd1cfa194c3a603e7186780824b04419'},{'_id':1})
2
{ "_id" : "4c4b1476238d3b4dd5000001" }

用户部分匹配查询(正则)
db.users.findOne( { 'last_name':/^Ba/})

1
1
db.users.findOne( { 'last_name':/^Ba/})

查询last_name以Ba开头的数据

为字段增加索引来增加范围查询的速度
db.users.find({'addresses.zip':{'gt:10019,lt':10040}})

1
1
db.users.find({'addresses.zip':{'gt:10019,lt':10040}})

给addresses.zip增加索引,这样查询会更快。

运算符查询(inall,ninin:如果任意参数在引用集合中,则匹配
all使nin:如果没有参数在引用的集合里,则匹配
db.products.find( { 'main_cat_id':{'$in':[ '6a5b1476238d3b4dd5000048','6a5b1476238d3b4dd5000049']}})

1
1
db.products.find( { 'main_cat_id':{'$in':[ '6a5b1476238d3b4dd5000048','6a5b1476238d3b4dd5000049']}})

in,all使用索引。

布尔运算符(ne,not,or,nor,and,exists)
ne:使使not:不匹配结果。
or:nor:所有条件都不匹配。
and:exists:判断元素是否存在。




选择器篇
我们可以使用点 (.) 分离有关关键字查询此类对象。这种选择器可以指定任意深度。

数组(下标,elemMatch,size)
查询数组时候选择器可以使用下标
db.products.find({ 'tags.0':'tools'})

1
1
db.products.find({ 'tags.0':'tools'})

$elemMatch:如果提供的所有词语在相同的子文档中,则匹配。

从逻辑上来讲,仅当我们需要匹配多个或者更多属性的子文档才使用$elemMatch。

$size:如果子文档数组大小与提供的文本值相同,则匹配。

JavaScript查询运算符
db.reviews.find({'$where':'function(){ return this.helpful_votes >= 3;}'})
db.reviews.find({ '$where':'this.helpful_votes >= 3' })

2
1
db.reviews.find({'$where':'function(){ return this.helpful_votes >= 3;}'})
2
db.reviews.find({ '$where':'this.helpful_votes >= 3' })

在JavaScript范围内,$where执行任意JavaScript来选择文档。关键字this指向当前文档。
JavaScirpt不能使用索引,并且带来大量费用。而且容易被注入攻击。

Modmod[(quotient),(result)] 如果元素取余quotient等于result则匹配。quotient为除数,result为余数。
db.orders.find({sub_total:{$mod:[6196,0]}})

1
1
db.orders.find({sub_total:{$mod:[6196,0]}})

$slice选择返回文档的子集
返回前12条评论或者返回最后5条评论

跳过前24条评论并且限制评论为12条,而且仅返回评论和评分

排序
有益的评论和评分降序查询





posted @ 2021-01-14 19:30  _Shing  阅读(168)  评论(0)    收藏  举报