MongoDB QueryData
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 results should look like:
{ "_id" : 10, "deptno" : 10, "dname" : "ACCOUNTING", "loc" : "NEW YORK" } { "_id" : 20, "deptno" : 20, "dname" : "RESEARCH", "loc" : "DALLAS" } { "_id" : 40, "deptno" : 40, "dname" : "OPERATIONS", "loc" : "BOSTON" } { "_id" : 50, "deptno" : 40, "dname" : "OPERATIONS V2", "loc" : "BOSTON" } { "_id" : 30, "deptno" : 30, "dname" : "SALES", "loc" : "CHICAGO" }
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 will be unique:
db.dept.find({_id:10})
In the emp collection, the _ids are system generated and generally along the lines of: '5a0727e99ba81dee9b1cc6a3', so less easy to use!
List all the records in emp:
db.emp.find().pretty()
and pick an _id from the collection and then try and find one record.
For example (note, your object id will be different):
db.emp.find( {_id : ObjectId("5a0727e99ba81dee9b1cc6a3")}).pretty()
The function ObjectId() must be used to convert the value into an object id.
Next Step
MongoDB Aggregation Pipeline