MongoDB Learning Four: Query (cont.)

Source: Internet
Author: User

Go on to the next chapter and continue to introduce MONGODB queries.

Querying on Embedded Documents

There are two ways to query embedded sub documents: Querying the entire document or querying individual key-value pairs.

Querying the entire child document is the same as the normal query.

We have a document:

{     "name": {           "first": "Joe",           "last": "Schmoe"           },      "age": 45 }

We can look for someone named Joe Schmoe:

Db.people.find ({"name": {"First": "Joe", "Last": "Schmoe"}})

However, querying a child document must match exactly. If Joe decides to add an intermediate name field, the query above will not be valid.

And, this type of query is also order-sensitive, {"Last": "Schmoe", "First": "Joe"}, so the query is also mismatched.

This is usually not the case if you are looking for a sub-document key:

Db.people.find ({"Name.last": "Schmoe", "Name.first": "Joe"})

Let's look at this data:

{   "content": "...",   "Comments": [         {             "author": "Joe",             " Score ": 3,             " comment ":" nice Post "          },         {             " author ":" Mary ",             " Score ": 6,             " comment ":" terrible post "          }    ]}

Now we want to find comments for Joe and score more than 5.

First of all, we can't query this

Db.blog.find ({"Comments": {"author": "Joe", "score": {"$gte": 5}})

Inline document matching requires the entire document to match exactly, rather than matching the comments key.

Also, we can't use

Db.blog.find ({"Comments.author": "Joe", "Comments.score": {"$gte": 5}})

Because comments that meet author conditions and score-compliant comments may not be the same. That means it will return the document that was just shown. Because "author" is implemented in the first comment, "Score" is implemented in the second comment.

What's the right thing to do?

Db.blog.find ({"Comments": {"$elemMatch": {"author": "Joe", "score": {"$gte": 5}}})

"$elemMatch" groups the qualifying conditions, which are only used when multiple key operations are required for an inline document.

$where Queries

Key-value pairs are highly expressive queries, but they cannot be expressed by some queries.

At this point, the "$where" clause query comes out, which allows you to execute arbitrary javascript in your query

The most typical application is to compare the values of the two keys in the document for equality, such as a list of entries, and return the document if the two values are equal. Cases:

Db.foo.insert ({"Apple": 1, "banana": 6, "Peach": 3}) Db.foo.insert ({"Apple": 8, "spinach": 4, "Watermelon": 4})

In the second document, the values for "spinach" and "watermelon" are the same, so the document needs to be returned.

Db.foo.find ({"$where":function(){          for(varCurrentinch  This){               for(varOtherinch  This){                    if(Current!=other && This[current]== This[other]) {                               returnture; }              }          }          return false;}})

If the function returns True, the document is returned as part of the result.

Do not use "$where" when it is not necessary: it is much slower than the general query.

Cursors

The database uses cursors to return the execution results of find. The client's implementation of the cursor usually provides effective control over the final result.

You can limit the number of results, skip the partial results, sort the results according to any combination of keys in any direction, or perform some other powerful operation.

To create a cursor from the shell, you first populate the collection with some documents, then query them, and assign the results to a local variable. Here, create a simple collection, then query, and save the results with the cursor:

 for (i=0;i<100;i++) {      Db.collection.insert ({x:i});}
var cursor = Db.collection.find ()

The advantage of doing this is that you can view a single result at a time. If you place the result in a global variable or not in a variable, the MongoDB shell automatically iterates and automatically displays the first few documents.

That's what we've seen before, and in general we just want to see through the shell what's in the collection, rather than running the program in it, and that's the right design.

To iterate over the results, you can use the next method of the cursor. You can also use Hasnext to see if there are any other results. The typical traversal is as follows:

 while (Cursor.hasnext ()) {     = cursor.next ();      // Do Stuff}

The cursor class also implements an iterative interface, so it can be used in a foreach loop.

var cursor = db.people.find (); Cursor.foreach (function(x) {      print (x.name)}) 

When you use Find, the shell does not immediately query the database, but instead waits for the query to actually start asking for results, so that additional options can be attached to the query before execution.

Almost all methods of the cursor object return the cursor itself, so that the method chain can be formed in any order. The following types are equivalent:

var cursor = Db.foo.find (). Sort ({"X": 1}). Limit (1). Skip (ten); var cursor = Db.foo.find (). Limit (1). Sort ({"X": 1}). Skip (); var cursor = Db.foo.find (). Skip (+). Limit (1). Sort ({"X": 1});

At this point, the query has not been executed, and all of these functions simply construct the query. Suppose we execute

Cursor.hasnext ();

At this point, the query is sent to the server. The shell immediately gets the money 100 results or the first 4M data (the smaller between the two) so the next time you call next or Hasnext, you don't have to run selectmen to the server.

The client runs out of the first set of results, and the shell connects to the database again and asks for more results. This process continues until the cursor is exhausted or the result is returned.

MongoDB Learning Four: Query (cont.)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.