MongoDB query document
Syntax
The syntax format of MongoDB query data is as follows:
>db.COLLECTION_NAME.find()
The find() method displays all documents in an unstructured way.
If you need to read the data in an easy-to-read way, you can use the pretty() method. The syntax is as follows:
>db.col.find().pretty()
The pretty() method displays all documents in a formatted way. .
Example
In the following example we query the data in the collection col:
> db.col.find().pretty() { "_id" : ObjectId("56063f17ade2f21f36b03133"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "php中文网", "url" : "http://www.php.cn", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
In addition to the find() method, there is also a findOne() method, which only returns a document.
Comparison of MongoDB and RDBMS Where statements
If you are familiar with regular SQL data, you can better understand MongoDB's conditional statement queries through the following table:
Operation | Format | Example | Similar statements in RDBMS |
---|---|---|---|
equals | {<key>:<value> } | db.col.find({"by":"php中文网"}).pretty() | where by = 'php中文网' |
{<key>:{$lt:<value>}}
| ##db.col.find({"likes":{$lt:50}}). pretty() ##where likes < 50 | ##is less than or equal to | |
db.col.find({"likes":{$lte:50}}).pretty() | where likes <= 50 | is greater than | |
##db.col.find({"likes":{$gt:50}}).pretty()
| where likes > 50
| greater than or equal to | |
##db.col.find({"likes":{$gte:50}}).pretty() |
| where likes >= 50
| # is not equal to {<key>:{$ne:<value>}} |
db.col.find({"likes":{$ne:50}}).pretty() | where likes != 50 |
|