Python Mongodb Query Document
## Python3.x Python Mongodb Query Document
[ Python Mongodb](#)
MongoDB uses the find and find_one methods to query data in collections, which is similar to the SELECT statement in SQL.
The test data used in this article is as follows:
!(#)
### Query a Single Document
We can use the find_one() method to query a single document from a collection.
Query the first document in the **sites** collection:
## Example
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclientmycol = mydbx = mycol.find_one()print(x)
The output result is:
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'TUTORIAL', 'alexa': '10000', 'url': ''}
### Query All Data in a Collection
The find() method can query all data in a collection, similar to the SELECT * operation in SQL.
The following example finds all data in the **sites** collection:
## Example
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclientmycol = mydbfor x in mycol.find(): print(x)
The output result is:
{'_id': ObjectId('5b23696ac315325f269f28d1'), 'name': 'TUTORIAL', 'alexa': '10000', 'url': ''}{'_id': ObjectId('5b2369cac315325f3698a1cf'), 'name': 'Google', 'alexa': '1', 'url': 'https://www.google.com'}{'_id': ObjectId('5b236aa9c315325f5236bbb6'), 'name': 'Taobao', 'alexa': '100', 'url': 'https://www.taobao.com'}{'_id': ObjectId('5b236aa9c315325f5236bbb7'), 'name': 'QQ', 'alexa': '101', 'url': 'https://www.qq.com'}{'_id': ObjectId('5b236aa9c315325f5236bbb8'), 'name': 'Facebook', 'alexa': '10', 'url': 'https://www.facebook.com'}{'_id': ObjectId('5b236aa9c315325f5236bbb9'), 'name': 'Zhihu', 'alexa': '103', 'url': 'https://www.zhihu.com'}{'_id': ObjectId('5b236aa9c315325f5236bbba'), 'name': 'Github', 'alexa': '109', 'url': 'https://www.github.com'}
### Query Specified Fields
We can use the find() method to query specified fields by setting the field value to 1.
## Example
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclientmycol = mydbfor x in mycol.find({},{ "_id": 0, "name": 1, "alexa": 1 }): print(x)
The output result is:
{'name': 'TUTORIAL', 'alexa': '10000'}{'name': 'Google', 'alexa': '1'}{'name': 'Taobao', 'alexa': '100'}{'name': 'QQ', 'alexa': '101'}{'name': 'Facebook', 'alexa': '10'}{'name': 'Zhihu', 'alexa': '103'}{'name': 'Github', 'alexa': '109'}
Except for _id, you cannot specify both 0 and 1 in the same object. If you set a field to 0, all others will be 1, and vice versa.
The following example returns all fields except the alexa field:
## Example
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")mydb = myclient["tutorialdb
YouTip