要從MongoDB集合中查詢數(shù)據(jù),請(qǐng)使用MongoDB的find()方法。
以下代碼顯示了find()方法的語(yǔ)法
>db.COLLECTION_NAME.find()
find()方法返回所有文檔。
要以格式化的方式顯示結(jié)果,請(qǐng)使用pretty()方法。
>db.mycol.find().pretty()
>db.mycol.find().pretty() { "_id": ObjectId(2df22ad2222c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "url": "http://m.o2fo.com", "tags": ["mongodb", "database", "NoSQL"], "comments": "100" } >
findOne()方法只返回一個(gè)文檔。
下表顯示如何對(duì)具有條件的文檔執(zhí)行查詢。
操作 | 語(yǔ)法 | 例子 | RDBMS 等效 |
---|---|---|---|
相等 | {<key>:<value>} | db.mycol.find({"by":"w3cschool"}).pretty() | where by = 'w3cscjool' |
少于 | {<key>:{$lt:<value>}} | db.mycol.find({"comments":{$lt:50}}).pretty() | where comments < 50 |
小于等于 | {<key>:{$lte:<value>}} | db.mycol.find({"comments":{$lte:50}}).pretty() | where comments <= 50 |
大于 | {<key>:{$gt:<value>}} | db.mycol.find({"comments":{$gt:50}}).pretty() | where comments > 50 |
大于等于 | {<key>:{$gte:<value>}} | db.mycol.find({"comments":{$gte:50}}).pretty() | where comments >= 50 |
不等于 | {<key>:{$ne:<value>}} | db.mycol.find({"comments":{$ne:50}}).pretty() | where comments != 50 |
要在MongoDB中使用AND邏輯,請(qǐng)通過(guò)find()方法中的“,”分隔多個(gè)鍵,如下所示。
>db.mycol.find({key1:value1, key2:value2}).pretty()
以下代碼返回其字段為w3cschool和title字段為的文檔
>db.mycol.find({"by":"w3cschool","title": "MongoDB"}).pretty() { "_id": ObjectId(2df22ad2222c), "title": "MongoDB", "description": "MongoDB is no sql database", "by": "java2s", "url": "http://m.o2fo.com", "tags": ["mongodb", "database", "NoSQL"], "comments": "100" } >
它等于where子句是 where by='java2s' AND title='MongoDB Overview'.。
要根據(jù)OR條件查詢文檔,請(qǐng)使用 $or
關(guān)鍵字,如下所示:
>db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
以下查詢返回的字段為'w3cschool'或標(biāo)題字段為“MongoDB Overview”的文檔。
>db.mycol.find({$or:[{"by":"java2s"},{"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(2df22ad2222c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "java2s", "url": "http://m.o2fo.com", "tags": ["mongodb", "database", "NoSQL"], "comments": "100" } >
>db.mycol.find("comments": {$gt:10}, $or: [{"by": "java2s"}, {"title": "MongoDB Overview"}] }).pretty() >
等價(jià)sql是 'where comments>10 AND (by = 'java2s' OR title = 'MongoDB Overview')'。
MongoDB投影是只選擇必要的數(shù)據(jù)而不是整個(gè)文檔。
MongoDB的find()方法接受第二個(gè)可選參數(shù),它是要返回的字段列表。默認(rèn)情況下,MongoDB find()方法返回文檔中的所有字段。要僅選擇必填字段,請(qǐng)?jiān)O(shè)置值為1或0的字段列表。1值顯示字段,而0用于隱藏字段。
find()方法與投影的語(yǔ)法如下。
>db.COLLECTION_NAME.find({},{KEY:1})
以下示例顯示文檔的標(biāo)題。
>db.mycol.find({},{"title":1,_id:0}) >
更多建議: