Mongodb - Query

mongodb

How can we retrieve all documents in a collection?

o return all documents in a collection, call the find() method without a criteria document. For example, the following operation queries for all documents in the restaurants collection.

db.restaurants.find()
db.nettuts.find({gender: 'f'});
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]});

How can we sort the result of a query with Mongo?

Similar to SQL, Mongo provides the sort command. The command, like the find command takes a list of options to determine the sort order. Unlike SQL, however we specify ascending and descending differently. We do that as follows:

  • Ascending: -1
  • Descending: 1
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1});
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1, first: 1});

To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. 1 for ascending and -1 for descending.

db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } )

The above operation returns all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order. Perhaps the order of the sort direction significant (as typed)?

How can we limit the number of records returned?

Mongo provides the limit command, similar to MySQL and allows us to do just that.

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2);
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2).skip(2);  // limit, offset

What are conditional operators?

db.nettuts.find( { "age" : { "$lt" : 40 } } );
db.nettuts.find( { "age" : { "$lte" : 40 } } );
db.nettuts.find( { 'age' : { '$gt' : 47 } } );
db.nettuts.find( { 'age' : { '$gte' : 47 } } );
db.nettuts.find( { 'occupation' : { '$in' : [ "actor", "developer" ] } }, { "first" : 1, "last" : 1 } );

db.restaurants.find( { "grades.score": { $gt: 30 } } );

Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form:

{ <field1>: { <operator1>: <value1> } }

You can specify a logical conjunction (AND) for a list of query conditions by separating the conditions with a comma in the conditions document:

db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } );

You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator:

db.restaurants.find(
   { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)

The result set includes only the documents that match either conditions.

What is the purpose of the $nin operator?

It stands for not in. It is the opposite of the $in operator.

What is the purpose of the $not operator?

It is the negate operation.

How can we specify an and / or condition?

db.nettuts.find(
  { $or : [ { 
                  "gender" : "m", "occupation" : "developer" 
               } 
            ], 
     "age" : { "$gt" : 40 } 
  }, 
  { "first" : 1, "last" : 1, "occupation" : 1, "dob" : 1 } );

I believe that the second parameter to the find function is an object that is used to specify which columns should be included in the result.

How can we use regular expression with Mongo?

db.nettuts.find( { "first" : /(ma|to)*/i, "last" : /(se|de)/i  } );
db.nettuts.find( { "first" : /(jam?e*)*/i, "gender" : "f", "occupation" : "actor", "nationality" : "american"  } );

How can we filter based on an embedded field?

The query condition for an equality match on a field has the following form:

{ <field1>: <value1>, <field2>: <value2>, ... }

If the <field> is a top-level field and not a field in an embedded document or an array, you can either enclose the field name in quotes or omit the quotes. If the <field> is in an embedded document or an array, use dot notation to access the field. With dot notation, you must enclose the dotted name in quotes.

db.restaurants.find( { "borough": "Manhattan" } )
db.restaurants.find( { "address.zipcode": "10075" } )

How can we find documents which contains a field that is undefined?

You cannot use undefined in query documents. Consider the following document inserted into the people collection:

db.people.insert( { name : "Sally", age : undefined } )

The following queries return an error:

db.people.find( { age : undefined } )
db.people.find( { age : { $gte : undefined } } )

However, you can query for undefined values using $type, as in:

db.people.find( { age : { $type : 6 } } )

This query returns all documents for which the age field has value undefined.

Why do we have to quote a NumberLong field?

NumberLong is a 64 bit signed integer. You must include quotation marks or it will be interpreted as a floating point number, resulting in a loss of accuracy. For example, the following commands insert 9223372036854775807 as a NumberLong with and without quotation marks around the integer value:

db.json.insert( { longQuoted : NumberLong("9223372036854775807") } )
db.json.insert( { longUnQuoted : NumberLong(9223372036854775807) } )

When you retrieve the documents, the value of longUnquoted has changed, while longQuoted retains its accuracy:

db.json.find()
{ "_id" : ObjectId("54ee1f2d33335326d70987df"), "longQuoted" : NumberLong("9223372036854775807") }
{ "_id" : ObjectId("54ee1f7433335326d70987e0"), "longUnquoted" : NumberLong("-9223372036854775808") }
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License