Difference between revisions of "MongoDB QueryData"

From mi-linux
Jump to navigationJump to search
Line 34: Line 34:
  
  
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.emp.find().pretty()
 
  db.emp.find().pretty()
Line 40: Line 40:
  
 
Note the difference in the object ids returned.
 
Note the difference in the object ids returned.
 +
 +
 +
=== Find with query criteria ===
 +
 +
 +
If working with a large collection, you will not want all the documents returned.
 +
 +
Find all the employees in department 10:
 +
 +
db.emp.find({deptno:10})
 +
  
 
=== Find One document ===
 
=== Find One document ===
  
To find just one document - department 10:
+
To find just one document requires the use of the equivalent of a primary key field. This can be a field that the user takes responsibility to keep unique, such as the ''deptno'':
  
 
  db.dept.find({deptno:10})
 
  db.dept.find({deptno:10})
 +
 +
Or the object id can be used, which is will be unique:
 +
 +
db.dept.find({_id:10})
 +
 +
 +
Object ids will be discussed in a later section.
  
 
== Next Step ==
 
== Next Step ==
  
 
[[MongoDB_Aggregate_Pipeline|MongoDB Aggregation]] Pipeline
 
[[MongoDB_Aggregate_Pipeline|MongoDB Aggregation]] Pipeline

Revision as of 16:50, 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 with query criteria

If working with a large collection, you will not want all the documents returned.

Find all the employees in department 10:

db.emp.find({deptno:10})


Find One document

To find just one document requires the use of the equivalent of a primary key field. This can be a field that the user takes responsibility to keep unique, such as the deptno:

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

Or the object id can be used, which is will be unique:

db.dept.find({_id:10})


Object ids will be discussed in a later section.

Next Step

MongoDB Aggregation Pipeline