Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

Difference between revisions of "Find"

From NoSQLZoo
Jump to: navigation, search
m
m
Line 10: Line 10:
 
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'''.<br/><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'''.<br/><br/>
 
<code>.findOne()</code> limits the result to one document and also applies the <code>.pretty()</code> operation.
 
<code>.findOne()</code> limits the result to one document and also applies the <code>.pretty()</code> operation.
</div>
 
  
 
<div class="q nonum" data-lang="mongo">
 
<div class="q nonum" data-lang="mongo">

Revision as of 00:05, 9 April 2018

find() is used to filter and project.
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.

.findOne() limits the result to one document and also applies the .pretty() operation.

Show the name and capital for every country of "South America"

db.world.find(
  {continent:"South America"},
  {"_id":0, name:1, capital:1}
)