Understanding Query Objects

Throughout this chapter, the various methods all use a query object of some sort or another to define which documents to retrieve from a MongoDB collection. The query object is a standard JavaScript object with special property names that the MongoDB Node.js driver understands. These property names closely match the native queries that you can perform inside the MongoDB client, so you can easily transfer back and forth.

The properties of the query object are called operators because they operate on the data to determine whether a document should be included in the result set. These operators match the values of fields in a document against specific criteria. For example, to find all documents with a count value greater than 10 and name value equal to test, you use this query object:

{count:{$gt:10}, name:'test'}

The operator $gt specifies documents with a count field larger than 10. Using the standard colon syntax of name:'test' specifies that the name field must equal test. Notice that the query object has multiple operators. You can include several different operators in the same query.

When specifying fieldnames in a query object, you can use dot notation to specify subdocument fields. For example, consider the following object format:

{
  name:"test",
  stats: { height:74, eyes:'blue'}
}

You can query which users have blue eyes by using the following query object:

{stats.eyes:'blue'}

Table 15.1 lists the most commonly used operators.

Image
Image
Image

Table 15.1 query object operators that define the result set returned by MongoDB requests

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.239.111