Home > Articles > Web Development

  • Print
  • + Share This
Like this article? We recommend

Reading Data

To read data, you use the find() method and assign it to a cursor for iteration. Here is an example of a simple find query:

               var c = db.testData.find( { age: { $gt: 18 } }, { name: 1).limit(5)
               while ( c.hasNext() ) printjson( c.next() )

The query above returns the following document:

{ “_id” : ObjectId(“54666d7ce182f488849dee96”),“name” : “Jacks Teller” }

The unique ID for the document was created by MongoDB when the document was inserted.

The find query has a couple of parameters. The first parameter is the condition (called a query criterion) that finds users with an age greater than 18 in the previous example.

The second parameter (called the projection) of the query tells Mongo which fields should be or not be returned. In this case, the name field was displayed.

The second parameter can also contain helper methods (called modifiers) for data sorting, stepping, and limits. The 1 following a field name for the projection parameter of the query means that this field should be included in the result. Likewise, specifying 0 by the field name tells Mongo to omit that field from the result set.

  • + Share This
  • 🔖 Save To Your Account