Difference between revisions of "MongoDB QueryData"

From mi-linux
Jump to navigationJump to search
(Created page with " Show all data so far: db.deptCollection.find() Comes back messy, can make it better: db.deptCollection.find().pretty() Or just find one document: db.deptCollection.fi...")
 
Line 16: Line 16:
  
 
However, does mean you get back all the employees!
 
However, does mean you get back all the employees!
 +
 +
Since version 2.2 MongoDB's new $elemMatch can avoid this:
 +
 +
db.deptCollection.find({"employees.empno":7902},
 +
{ _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.

Revision as of 21:56, 18 October 2016


Show all data so far:

db.deptCollection.find()

Comes back messy, can make it better:

db.deptCollection.find().pretty()

Or just find one document:

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({"employees.empno":7902}, 
{ _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.