標籤:使用 os strong 伺服器 size 學習 c ad
1 find
find({查詢條件},{"key":1,"email":1}) 後面表示返回哪些鍵
2 可用的比較操作符
$lt , $lte,$gt,$gte
比如db.users.find({"age":{"$gte":18,"$lte":30}})
3不等於
find(...{"key":{"$ne":"value"}}
4 in
find(...{"key":{"$in":[1,2,3]}}
5 nin
find(...{"key":{"$nin":[1,2,3]}}
6 or
find( {"$or":[ {"key1":"value1"}, {"key2":"value2"} ]})
find( {"$or":[ {"key1": {"$in":["value1","value2"]} }, {"key2":"value2"} ]})
7$mod
find({"key": {"$mod":[5,1]}})
8 not
find({"key":{"$not":{"$mod":[5,1]}}})
9 and
find({"$and":[{"x":{"$lt":1}}, {"x":4}]})
這個匹配{"x"[0,4]}
等同於 find({"x":{"$lt":1,"$in":[4]}})
10 關於null
find( {"y": null } )---不僅會找到y:null的文檔,還會找到不存在此欄位的文檔。
可以使用
find( {"z": {"$in" : [null],"$exists":true}})
11 查詢使用Regex ---PCRE
查詢名為Joe或者joe
find({"name": /joe/i})
find({"name": /joe?/i})
find({"name": /^joe/})
12 查詢數組
find({"fruit":"value1"}) 也就是數組中包含value1就可以搜到!
13數組中包含多個
find( {"fruit": {"$all":["value1","value2"]}}
也就是數組既包含value1又包含value2
14精確匹配
find({"fruit":【"value1","value2"]})
數組包含且僅僅包含這2個值才可以!
15數組的序號查詢
find({"fruit.2":"peach"})
16$size
find({"fruit":{"$size":3}})
17$slice
findOne(criteria,{"comments":{"$slice":10}})
返回前10條評論!
findOne(criteria,{"comments":{"$slice":-10}})
返回後10條評論!
findOne(criteria,{"comments":{"$slice":【23,10】}})
跳過23個元素,儘可能返回10個元素!
注意,只能對comments進行控制,其它欄位仍然返回!
18 $
模式:
comments:[{name:bob,email:xxx}, ................]
find({"comments.name":"bob"},{"comments.$":1})
返回第一個匹配的文檔。
19 數組的查詢
{"x": {"$gt" : 10,"$lt":20}}
如果此時x是一個數組,則任何一個元素滿足其中1個條件就可以認為匹配!
但是如果不是一個數組,則進行同時匹配!
20$elemMatch
首先,只會針對數組元素進行匹配
find({"x":{"$elemMatch":{"$gt":10,"$lt":20}})
21如果建立了索引
find({"x": {"$gt" : 10,"$lt":20}}).min({"x":10}).max({"x":20})
效果非常好!因為不是掃描所有索引,而是在部分索引裡進行掃描!
22 查詢內嵌文檔
find({"name":{"first":"joe","last":"schmoe"}})---精確匹配!
悲劇的是,這種查詢還是順序相關的!!!
注意:對於內嵌文檔,這種查詢都是精確匹配,必須用下面的方式!
23 更好的做法
find({"name.first“:"joe", "name.last":"schmoe"})
難道是or的關係???
24 請參考$elemMatch的方法!
25終極必殺技-where
----------------關於遊標
每次取100條或者4MB,取較小的一個。
find().skip(3).limit(10).sort({"key1":1,"key2":-1})._addSpecial("$maxscan",20)
._addSpecial("$min",20)
._addSpecial("$max",20)
._addSpecial("$showDiskLoc":true)
.snapShot()---會讓查詢變慢!
備忘:可以在啟動mongod時指定--noscripting,關閉js的運行!---關閉伺服器端指令碼!