MongoDB 查詢語法與常用查詢語句總結
阿新 • • 發佈:2018-11-02
MongoDB 常用查詢語句總結
先來一波查詢語句語法的基本解釋:
列子:
db.mycol.find({"likes": {$gt:10}, $or: [{"by": "yiibai tutorials"}, {"title": "MongoDB Overview"}]}
,{likes:1,ip:1}
)
find裡面,可以填入兩個大括號,第一個表示篩選條件,第二個表示你想要返回的欄位
先說第二個,稍微簡單一些:
{likes:1,ip:0}表示返回likes欄位,返回ip欄位,那麼剩餘其他欄位呢?不返回!1表示返回,0表示不返回,當然
{likes:1,ip:0}這種情況是不允許的,執行的時候會報錯。
再說第一個,語法比較多:
第一點: 所有的篩選條件都放在這裡面。用{}包圍
第二點:如果你是要查name=“jay”的資料,直接用
db.mongoTest.find({name:'jay'})
第三點: 如果你還有其他and條件就需要使用到and操作符。
db.mycol.find({$and:[{"by":"aaa"},{"title": "bbb"}]})`
這條語句的意思就是查詢by=aaa並且title=bbb的資料。
`db.mycol.find({$and:[{"age":{$gt:10}},{"title": "bbb"}]})
這條語句表示你想查詢age大於10並且title=bbb的資料。
第四點
db.mycol.find({$or: [ {key1: value1}, {key2:value2} ] })
第五點:如果你既有and又有or。如果and裡面有兩個條件,or裡面也有兩個條件呢?
db.mycol.find({"likes": {$gt:10},
$or: [{"by": "yiibai tutorials"},{"title": "MongoDB Overview"}]})
db.mycol.find({$and: [{content:"cs"},{likes: {$gt:10}}], $or: [{"by": "yiibai tutorials"},{"title": "MongoDB Overview"}]})
等效於關係型資料庫中的大於小於等操作符列表
操作 | 示例 | 等效語句 |
---|---|---|
相等 | db.mycol.find({“by”:“yiibai”}) | where age = 30 |
小於 | db.mycol.find({“likes”:{$lt:50}}) | where age < 30 |
小於等於 | db.mycol.find({“likes”:{$lte:50}}) | where age <= 30 |
大於 | db.mycol.find({“likes”:{$gt:50}}) | where age > 30 |
大於等於 | db.mycol.find({“likes”:{$gte:50}}) | where age >= 30 |
不想等 | db.mycol.find({“likes”:{$ne:50}}) | where age != 30 |
順帶提一句:在xml檔案寫sql語句不能直接寫<=,需要這樣寫:
age <= 30
或者使用<![CDATA[ sql內容 ]]>將sql語句包裹住:
where
<![CDATA[
age <= 30
]]>