Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


MongoDB Query and Operators


You can perform ad hoc queries on the database using the find or findOne functions and a query document. All queries in MongoDB have the scope of a single collection. You can query for ranges, set inclusion, inequalities, and more by using $ conditionals. Some queries cannot be expressed as query documents, even using $ conditionals.


MongoDB Find Query

Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a document and pass as a parameter to the find() method.
The find() method returns query results in a cursor, which is an iterable object that yields documents. There are a lot of metaoperations you can perform on a cursor, including skipping a certain number of results, limiting the number of results returned, and sorting results.

The find method is used to perform queries in MongoDB. Querying returns a subset of documents in a collection, from no documents at all to the entire collection. Which documents get returned is determined by the first argument to find, which is a document specifying the query to be performed.
An empty query document (i.e., {}) matches everything in the collection. If find isn't given a query document, it defaults to {}. For example, the following:


> db.c.find()


returns everything in the collection c.
When we start adding key/value pairs to the query document, we begin restricting our search. This works in a straightforward way for most types. Integers match integers, booleans match booleans, and strings match strings. Querying for a simple type is as 45 easy as specifying the value that you are looking for. For example, to find all documents where the value for "age" is 27, we can add that key/value pair to the query document:


> db.users.find({"age": 27})


If we have a string we want to match, such as a "username" key with the value "joe", we use that key/value pair instead:


> db.users.find({"username": "joe"})


Multiple conditions can be strung together by adding more key/value pairs to the query document, which gets interpreted as "condition1 AND condition2 AND ... AND condition." For instance, to get all users who are 27-year-olds with the username "joe," we can query for the following:


> db.users.find({"username": "joe", "age": 27})


Specifying Which Keys to Return
Sometimes, you do not need all the key/value pairs in a document returned. If this is the case, you can pass a second argument to find (or findOne) specifying the keys you want. This reduces both the amount of data sent over the wire and the time and memory used to decode documents on the client side.
For example, if you have a user collection and you are interested only in the "user name" and "email" keys, you could return just those keys with the following query:


> db.users.find({}, {"username": 1, "email": 1})
{
"_id": ObjectId("4ba0f0dfd22aa494fd523620"),
"username": "joe",
"email": "joe@example.com"
}


As you can see from the previous output, the "_id" key is always returned, even if it isn't specifically listed. You can also use this second parameter to exclude specific key/value pairs from the results of a query. For instance, you may have documents with a variety of keys, and the only thing you know is that you never want to return the fatal weakness" key:


> db.users.find({}, {"fatal weakness": 0})


This can even prevent "_id" from being returned:


> db.users.find({}, {"username" : 1, "_id" : 0})
{
"username" : "joe",
}


Query Criteria and Operator

Queries can go beyond the exact matching described in the previous section; they can match more complex criteria, such as ranges, OR-clauses, and negation. $lt, $lte, $gt, and $gte are all comparison operators, corresponding to <, <=, >, and >=, respectively. They can be combined to look for a range of values. For example, to look for users who are between the ages of 18 and 30 inclusive, we can do this:


> db.users.find({age : {$gte : 18, $lte : 30}})


These types of range queries are often useful for dates. For example, to find people who registered before January 1, 2007, we can do this:


> start = new Date(01/01/2007)
> db.users.find({registered : {$lt : start}})


If you want to find all users who do not have the username "joe", you can query for them using this:


> db.users.find({username : {$ne : joe}})


$ne can be used with any type.


OR Queries

There are two ways to do an OR query in MongoDB. "$in" can be used to query for a variety of values for a single key. "$or" is more general; it can be used to query for any of the given values across multiple keys. If you have more than one possible value to match for a single key, use an array of criteria with "$in". For instance, suppose we were running a raffle and the winning ticket numbers were 725, 542, and 390. To find all three of these documents, we can construct the following query:


> db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})


The opposite of "$in" is "$nin", which returns documents that don't match any of the criteria in the array. If we want to return all of the people who didn't win anything in the raffle, we can query for them with this:


> db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})


This query returns everyone who did not have tickets with those numbers.

$Not
"$not" is a metaconditional: it can be applied on top of any other criteria. As an example, let's consider the modulus operator, "$mod". "$mod" queries for keys whose values, when divided by the first value given, have a remainder of the second value:


> db.users.find({"id_num" : {"$mod" : [5, 1]}})


The previous query returns users with "id_num"s of 1, 6, 11, 16, and so on. If we want, instead, to return users with "id_num"s of 2, 3, 4, 5, 7, 8, 9, 10, 12, and so on, we can use "$not":


> db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})


"$not" can be particularly useful in conjunction with regular expressions to find all documents that don't match a given pattern.

$all
If you need to match arrays by more than one element, you can use "$all". This allows you to match a list of elements. For example, suppose we created a collection with three elements:


> db.food.insert({"_id" : 1, "fruit" : ["apple", "banana", "peach"]})
> db.food.insert({"_id" : 2, "fruit" : ["apple", "kumquat", "orange"]})
> db.food.insert({"_id" : 3, "fruit" : ["cherry", "banana", "apple"]})


Then we can find all documents with both "apple" and "banana" elements by querying with "$all":


> db.food.find({fruit : {$all : ["apple", "banana"]}})

{"_id" : 1, "fruit" : ["apple", "banana", "peach"]}
{"_id" : 3, "fruit" : ["cherry", "banana", "apple"]}


Order does not matter. Notice "banana" comes before "apple" in the second result. Using a one-element array with "$all" is equivalent to not using "$all". For instance, {fruit : {$all : ['apple']} will match the same documents as {fruit : 'apple'}. If you want to query for a specific element of an array, you can specify an index using the syntax key.index:


> db.food.find({"fruit.2" : "peach"})


Arrays are always 0-indexed, so this would match the third array element against the string "peach".


$size

A useful conditional for querying arrays is "$size", which allows you to query for arrays of a given size. Here's an example:


> db.food.find({"fruit" : {"$size" : 3}})


One common query is to get a range of sizes. "$size" cannot be combined with another $ conditional (in this example, "$gt"), but this query can be accomplished by adding a "size" key to the document.


The $slice operator

As mentioned earlier in this chapter, the optional second argument to find specifies the keys to be returned. The special "$slice" operator can be used to return a subset of elements for an array key. For example, suppose we had a blog post document and we wanted to return the first 10 comments:


> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : 10}})


Alternatively, if we wanted the last 10 comments, we could use -10:


> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : -10}})


"$slice" can also return pages in the middle of the results by taking an offset and the number of elements to return:


> db.blog.posts.findOne(criteria, {"comments" : {"$slice" : [23, 10]}})


This would skip the first 23 elements and return the 24th through 34th. If there are fewer than 34 elements in the array, it will return as many as possible.

$where The MongoDB $where operator is used to match documents that satisfy a JavaScript expression. A string containing a JavaScript expression or a JavaScript function can be pass using the $where operator. The JavaScript expression or function may be referred as this or obj. Here is below sample json which is exists in table3 name collection


{ "_id" : ObjectId("52873b364038253faa4bbc0e"), "student_id" : "STU002", "sem" : "sem1", "english" : "A", "maths" : "A+", "science" : "A"}

{ "_id" : ObjectId("52873b5d4038253faa4bbc0f"), "student_id" : "STU001", "sem" : "sem1", "english" : "A+", "maths" : "A+", "science" : "A"}

{ "_id" : ObjectId("52873b7e4038253faa4bbc10"), "student_id" : "STU003", "sem" : "sem1", "english" : "A+", "maths" : "A", "science" : "A+"}


If we want to select all documents from the collection which satisfying the condition - The grade of english must be same as science the following mongodb command can be used :


> db.table3.find( { $where: function() { return (this.english == this.science) }}).pretty();
{
"_id" : ObjectId("52873b364038253faa4bbc0e"),
"student_id" : "STU002",
"sem" : "sem1",
"english" : "A",
"maths" : "A+",
"science" : "A"
}

{
"_id" : ObjectId("52873b7e4038253faa4bbc10"),
"student_id" : "STU003",
"sem" : "sem1",
"english" : "A+",
"maths" : "A",
"science" : "A+"
}

> db.table3.find( { $where: function() { return (this.english == this.science) }}).pretty();
{ "_id" : ObjectId("52873b364038253faa4bbc0e"),
"student_id" : "STU002",
"sem" : "sem1",
"english" : "A",
"maths" : "A+",
"science" : "A"
}

{ "_id" : ObjectId("52873b7e4038253faa4bbc10"),
"student_id" : "STU003",
"sem" : "sem1",
"english" : "A+",
"maths" : "A",
"science" : "A+"
}


If we want to get the above output the other mongodb statements can be written as below -


> db.table3.find( { $where: function() { return (obj.english == obj.science)}}).pretty();
> db.table3.find( "this.english == this.science").pretty();


     << Previous
Next >>