Difference between revisions of "MongoDB QueryData"

From mi-linux
Jump to navigationJump to search
Line 26: Line 26:
 
=== Find all documents ===
 
=== Find all documents ===
  
For example, show all the data so far in the dept collection:
+
For example, show all the data so far in the ''dept'' collection:
 
  db.dept.find()
 
  db.dept.find()
 +
 +
And the ''emp'' collection:
 +
 +
db.emp.find()
 +
  
 
The data comes back messy. The pretty() function can be used to improve the layout::
 
The data comes back messy. The pretty() function can be used to improve the layout::
  
  db.dept.find().pretty()
+
  db.emp.find().pretty()
 +
 
  
 +
Note the difference in the object ids returned.
  
 
=== Find One document ===
 
=== Find One document ===

Revision as of 17:43, 11 November 2017

Main Page >> MongoDB >>MongoDB Workbook >> Querying Collections

Querying a collection

The find() function can be used to query the documents.

The format is:

 db.collectionName.find(optional_query_criteria)

Where the query_criteria follows a pattern:

 db.collectionName.find({keyField: "value"})

Note:

  • the criteria is enclosed in curly brackets: {}
  • the value needs quotes if it is a string or date value
  • all names and values are case sensitive
  • quotes are optional for the fieldName, so long as they do not contain spaces


Find all documents

For example, show all the data so far in the dept collection:

db.dept.find()

And the emp collection:

db.emp.find()


The data comes back messy. The pretty() function can be used to improve the layout::

db.emp.find().pretty()


Note the difference in the object ids returned.

Find One document

To find just one document - department 10:

db.dept.find({deptno:10}).pretty()


Next Step

MongoDB Aggregation Pipeline