Difference between revisions of "MongoDB QueryData"

From mi-linux
Jump to navigationJump to search
Line 13: Line 13:
  
 
The format is:
 
The format is:
<pre style="font:blue">
+
<pre style="color: blue">
 
  db.deptCollection.find({"fieldName": "value"})
 
  db.deptCollection.find({"fieldName": "value"})
 
</pre>
 
</pre>

Revision as of 22:49, 18 October 2016

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

Querying a collection

Show all data so far:

db.deptCollection.find()

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

db.deptCollection.find().pretty()

The find() function can be used to find just one document.

The format is:

 db.deptCollection.find({"fieldName": "value"})

The fieldName must be in quotes, the value needs quotes if it is a string or date value.

For example, find department 10:

db.deptCollection.find({"deptno":10}).pretty()

Finding an employee means using the array name too:

db.deptCollection.find({"employees.empno":7902}).pretty()

However, does mean you get back all the employees!

Since version 2.2 MongoDB's new $elemMatch can avoid this:

db.deptCollection.find({"deptno":20},  
  { _id: 0, employees: {$elemMatch: {empno: 7902}}}).pretty()

$elemMatch limits the contents of the employees array to contain only the first element matching the $elemMatch condition.

_id is a unique value automatically generated by MongoDB (like a Primary Key). To see it:

db.deptCollection.find({"deptno":20},  
  { employees: {$elemMatch: {empno: 7902}}}).pretty()

This is akin to a SQL query:

 SELECT * FROM Emp WHERE deptno=20 AND empno = 7902

However, could you just query using the empno?

Next Step

Updating the collection