Query Criteria
Find
db.foo.find(query, projection)
Query: which documents to find
projection: Fields to be included (optional)
Example :
db.foo.find({_id:1}, {_id:1}) {"_id":1}
In the above query we have asked to return the _ID field with a matching criteria of 1
Comparison Operators (pretty self explanatory with examples
Example:
db.foo.find({_id: {$gt:5, }}, {_id:1}) // greater than operator and so forth db.foo.find({_id: {$lt;}}, {_id:1}) db.foo.find({_id: {$gte:5}}, {_id:1}) db.foo.find({_id: {$lte:5}}, {_id:1}) //specify a range db.foo.find({_id: $gt:2, $lt: 6}}, {_id:1}) //you get the picture //Negate the selection example db.foo.find({_id: {$not {$lt:5}}}, {_id:1}) // negation is often used with strict equality rather than not // Search for discrete values (the "IN" operator) // Note: Its either 1 or 3 and not between 1 and 3 db.foo.find({_id: {$in: [1,5]}}, {_id:1}) // find values not in (1,3) db.foo.find({_id: {$nin: [1,5]}}, {_id:1})
Searching for Arrays
db.animals.find({_id:1}).pretty() { "_id":1 "name": "cat", "tags" : ["land", "cute"], "info" : {"type": "mammal", "color":"red"} }
We will try and match the fields in the array “tags”. Lets try and find an animal with the tag “cute”
>db.find.animals({tags:'cute'},{name:1}) {"id":1, "name": "cat"} {"id":2, "name": "dog"} {"id":3,"name": "rabbit"} {"id":4, "name": "mice"} // This was a strict equality operator, which mean cute with a Capital "C" // would not work. So are the field names // Lets look for a range now, the range is an either or operator >db.find.animals({tags:{$in: ['cute','ocean']}},{name:1}) {"id":1, "name": "cat"} {"id":2,"name":"shark"} {"id":3,"name": "dolphin"} {"quot;id":4,"name":"penguin"} // to have a range with an and operator >db.find.animals({tags:{ ['cute','ocean']}},{name:1}) {"id":3, "name": "dolphin"} {"id":4, "name": "penguin"} // similarly for the not in operator >db.find.animals({tags:{"$nin": ['cute']}},{name:1}) {"id":2, "name": "shark"}
Searching for sub documents
>db.animals.find({_id:1}).pretty() { "_id":1 "name": "cat", "tags" : ["land", "cute"], "info" : {"type": "mammal", "color":"red"} } // I want to find information of the nested document info. //But since Mongo does not enforce a schema the structure of the info //sub document can be anything But its not an issue with Mongo //we can use the .dot notation to search for the inner document >db.animals.find({"info.canfly":true}).pretty() { "_id":6 "name": "duck", "tags" : ["land", "cute"], "info" : {"type": "bird", "canfly":"true"} } // Notice that the info on document 1 is completely different from document 6. // this is fine because Mongo does not enforce the schema.
Quirks in a accessing sub documents
In the figure above notice that the first qry is searching for a type=bird and canfly=true and surely enough we get a row back as the result
The same query when repeated, but the conditions reversed does not yeild any results. This is because Mongo is trying to match the document exactly as it is. the condition specified is the reverse of what is specified in the document. To Over come this we can use the dot(.) notation. As you can see from above the third query with the “dot” notation returns results.
Difference between null and Exists
1. db.animals.find({"info.canfly":true , {name:1}) 2. db.animals.find({"info.canfly":null, {name:1}) 3. db.animals.find({"info.canfly":{$exist:false)}, {name:1})
In the code above line 1 is a standard query syntax.
Line 2 is actually querying for an element that is null or an element that does not exist. Hence it will contain a document set with tags that are absent or tags that are null.
If we specifically want to return documents with or without certain tags, we need to use the $Exist (PELLS $ E X I S T) tag. as seen in line 3
AND Operator
The AND operator is indicated b a comma between arguments like below
>db.animals.find({"info.type":’bird’, "tags"=’cute’}, {name:1}
// animal with info type bird AND tag cute
MongoDB Projections
Projections simply means the fields that will be returned by your select query
>db.animals.find({_id=1"}, {name:1}) // when you specify name=1 , it will return you the name field as well as the ID // field. If you specify name=0, the column will be eliminated from your // result and all other columns will be returned. // ID will always be returned by default unless you explicitly make it zero // You cannot mix fields i.e the query name=1, address=1 is fine. // so is name=0, address=0,; both will be omitted // but name=1, address=0 will not be tolerated by Mongo. It will throw an error
Cursor

When your application shoots a query to Mongo Server, it might span many, many documents, more than you ever need or more than that can fit into memory. To support efficient retrieval of documents , Mongo creates a cursor. Mongo will populate a cursor and give you a batch of documents each time.On the client side the aplication as well as well as the shell will retrieve a batch of documents from the cursor, and finally close the cursor. A client can signal the server to close the cursor before all the documents have been exhausted, there by saving time and data transfer across the network and freeing the server to serve other calls.
Cursor Operations in the shell
In the example above the first statement returns all the records from the cursor. This cursor can be captured into a variable as above and then we can iterate through the variable
Cursor variable provides information such as the size (number or records) ,if there is another record present (hasnext()), or iterate using a foreach loop etc. For more details see the official docs.
Sorting can be done be done by changing the sort order from -1 to 1 for the field that you are interested in. ( 1 : ascending and -1 descending).
Notice in example where ID is the only projection but we are sorting by name. The results clearly show that the ID is jumbled up and the sorting had been done by the name. This proves that sorting happens on the server and not on the client side.
Finally the last example shows that you sort on documents with in documents using the dot notation.In the first example one we sort info and name in ascending and in the second example the document set info within the main document has been sorted asc by inf.type and name desc. Notice that Name is part of the main document while info.type is part o the sub document info within main.
To Limit the results you can use the limit command which returns only the number of documents specified in the limit. The limit happens on the server side, therefore it makes the query more efficient by limiting results where required. Combining sorting and limiting records is useful but often times we might want to do server side paging by skipping un-needed records. This can be done by using the skip() function. In the above example we skip the first record.
When you want to find exactly one record, you can skip the cursors and go for the findone() command which returns exactly one record. The findone() command does not return a cursor, so i you were to capture it in a variable and try to do a findnext() on the variable, you would receive an error.
So that pretty much covers the fundamentals on MongoDB queries.
Next we will look at indexing in MongoDB. I promise you, it will be really interesting
For all your application development needs, visit www.verbat.com for a fiscally conscious proposal that meets your needs ( So I can keep this blog going as well!!!!)
Alternatively click through the link if you found this article interesting. (This will help the companies Search engine rankings)
Leave a Reply