MongoDB QueryData

From mi-linux
Jump to navigationJump to search

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