要想查詢 MongoDB 集合中的數(shù)據(jù),使用 find()
方法。
find()
方法的基本格式為:
>db.COLLECTION_NAME.find()
find()
方法會(huì)以非結(jié)構(gòu)化的方式來顯示所有文檔。
用格式化方式顯示結(jié)果,使用的是 pretty()
方法。
>db.mycol.find().pretty()
>db.mycol.find().pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
除了 find()
方法之外,還有一個(gè) findOne()
方法,它只返回一個(gè)文檔。
如果想要基于一些條件來查詢文檔,可以使用下列操作。
操作 | 格式 | 范例 | RDBMS中的類似語句 |
---|---|---|---|
等于 | {<key>:<value> } |
db.mycol.find({"by":"tutorials point"}).pretty() |
where by = 'tutorials point' |
小于 | {<key>:{$lt:<value>}} |
db.mycol.find({"likes":{$lt:50}}).pretty() |
where likes < 50 |
小于或等于 | {<key>:{$lte:<value>}} |
db.mycol.find({"likes":{$lte:50}}).pretty() |
where likes <= 50 |
大于 | {<key>:{$gt:<value>}} |
db.mycol.find({"likes":{$gt:50}}).pretty() |
where likes > 50 |
大于或等于 | {<key>:{$gte:<value>}} |
db.mycol.find({"likes":{$gte:50}}).pretty() |
where likes >= 50 |
不等于 | {<key>:{$ne:<value>}} |
db.mycol.find({"likes":{$ne:50}}).pretty() |
where likes != 50 |
在 find()
方法中,如果傳入多個(gè)鍵,并用逗號(hào)(,
)分隔它們,那么 MongoDB 會(huì)把它看成是 AND 條件。AND 條件的基本語法格式為:
>db.mycol.find({key1:value1, key2:value2}).pretty()
下例將展示所有由 “tutorials point” 發(fā)表的標(biāo)題為 “MongoDB Overview” 的教程。
>db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
對(duì)于上例這種情況,RDBMS 采用的 WHERE 子句將會(huì)是:where by='tutorials point' AND title='MongoDB Overview'。你可以在 find 子句中傳入任意的鍵值對(duì)。
若基于 OR 條件來查詢文檔,可以使用關(guān)鍵字 $or。 OR 條件的基本語法格式為:
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
下例將展示所有由 “tutorials point” 發(fā)表的標(biāo)題為 “MongoDB Overview” 的教程。
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
下例所展示文檔的條件為:喜歡數(shù)大于 100,標(biāo)題是 “MongoDB Overview”,或者是由 “tutorials point” 所發(fā)表的。響應(yīng)的 SQL WHERE 子句為:where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>