Importance and order of functions in MongoDB when retrieving data
When running week 1 homework scripts we get following results:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cd ~/mongo-course/week1/homework# | |
# python hw1-2.21394489c9ad.py | |
The answer to Homework One, Problem 2 is 1815 | |
# python hw1-3.e594fc84d4ac.py | |
Bottle v0.11.6 server starting up (using WSGIRefServer())... | |
Listening on http://localhost:8080/ | |
Hit Ctrl-C to quit. | |
ip6-localhost - - [19/Dec/2013 01:14:47] "GET /hw1/2 HTTP/1.1" 200 2 | |
ip6-localhost - - [19/Dec/2013 01:14:49] "GET /hw1/3 HTTP/1.1" 200 2 | |
ip6-localhost - - [19/Dec/2013 01:14:51] "GET /hw1/4 HTTP/1.1" 200 2 | |
ip6-localhost - - [19/Dec/2013 01:14:52] "GET /hw1/5 HTTP/1.1" 200 2 | |
ip6-localhost - - [19/Dec/2013 01:14:55] "GET /hw1/50 HTTP/1.1" 200 3 | |
# from another terminal | |
root@mongo2:~/hw1# curl -v 127.1:8080/hw1/50 | |
* About to connect() to 127.1 port 8080 (#0) | |
* Trying 127.0.0.1... connected | |
> GET /hw1/50 HTTP/1.1 | |
> User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3 | |
> Host: 127.1:8080 | |
> Accept: */* | |
> | |
* HTTP 1.0, assume close after body | |
< HTTP/1.0 200 OK | |
< Date: Thu, 19 Dec 2013 01:14:55 GMT | |
< Server: WSGIServer/0.1 Python/2.7.3 | |
< Content-Length: 3 | |
< Content-Type: text/html; charset=UTF-8 | |
< | |
53 | |
* Closing connection #0 | |
The code is simple. There is only one line of code that is interesting.
iter = collection.find({},limit=1, skip=n).sort('value', direction=1)
There are two methods executed one after another. The first one is find and the second sort. At fist it looks like the sort method is only applied to the results returned by find but this is not truth.
What is actually happening is:
- The find method returns all documents from the data base (the order of the values is determined by the database what can be read as random; this would be the equivalent of a select * from table statement in SQL)
- The list is then sorted base on the value. The value represent here one of the document attributes.
- After the returned documents (i.e. returned rows from table in RDMS data base) are sorted we skip the first 'n' rows and return a single element.
No comments:
Post a Comment