Difference between revisions of "Find"
m |
m |
||
Line 25: | Line 25: | ||
The second parameter selects what fields to include. If the second parameter is not present the default action is to include all the fields in the result documents.<br/> | The second parameter selects what fields to include. If the second parameter is not present the default action is to include all the fields in the result documents.<br/> | ||
To hide a field, <code><field>:0</code> is used. The other fields won't be removed.<br/> | To hide a field, <code><field>:0</code> is used. The other fields won't be removed.<br/> | ||
− | Using <code><field>:1</code> will include that field and hide all the others except the <code>_id</code> and other fields set to 1<br/> | + | Using <code><field>:1</code> will include that field and hide all the others except the <code>_id</code> and other fields set to 1.<br/> |
Passing an empty (<code>{}</code>) second parameter hides all fields except the <code>_id</code> field, to hide <code>_id</code> it has to be explicitly set to 0. | Passing an empty (<code>{}</code>) second parameter hides all fields except the <code>_id</code> field, to hide <code>_id</code> it has to be explicitly set to 0. | ||
</div> | </div> |
Revision as of 12:52, 27 July 2015
#ENCODING import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16') #MONGO from pymongo import MongoClient client = MongoClient() client.progzoo.authenticate('scott','tiger') db = client['progzoo'] #PRETTY import pprint pp = pprint.PrettyPrinter(indent=4) #CODE from bson.code import Code
find()
is used to query documents. It takes a query
parameter and an optional projecetion
parameter, and returns a cursor.
By default find()
returns a cursor containing all the documents in the collection it is used on. This is the same as find({})
To get all the documents with a certain value, find(<field>:{"$eq":<value>}})
can be used, this can be simplified to find(<field>:<value>})
$eq
can be replaced with other conditional operators such as $lt
, $gt
to perform less than or greater than comparisons.
To query nested documents, dot notation can be used, e.g. parent.child.field
The second parameter selects what fields to include. If the second parameter is not present the default action is to include all the fields in the result documents.
To hide a field, <field>:0
is used. The other fields won't be removed.
Using <field>:1
will include that field and hide all the others except the _id
and other fields set to 1.
Passing an empty ({}
) second parameter hides all fields except the _id
field, to hide _id
it has to be explicitly set to 0.
Show the capital city and population of France
print(db.world.find({"name":"France"},{"_id":0,"population":1}))