This repository has been archived by the owner on Jul 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
new_way.txt
78 lines (49 loc) · 2.54 KB
/
new_way.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
>>> from mongokit import Connection
>>> con = Connection()
Let's say we have previously created 3 MongoDocuments : Blog, BlogPost and User.
These objects have to be reachable via the connection, so we register them :
>>> con.register([Blog, BlogPost, User])
and now we can play. Just like in the pymongo
api, we get to the collection via the connection - `con` in this case - and the db.
>>> con.mongokit.tutorial.find()
In this line, we query the collection named 'tutorial' (which is attached to the
db named 'mongokit') and fetch all documents in the collection (the pymongo's way).
Now enter the MongoDocument objects. Let's create a blog post:
>>> blogpost = con.mongokit.tutorial.BlogPost()
>>> blogpost['title'] = u'my title'
>>> blogpost['body'] = u'a body'
>>> blogpost['author'] = u'me'
>>> blogpost.save()
Note that this is quite the same as the current api. We just get the BlogPost object
via the collection. The main advantage of this approach is that we don't have to
bother about the collection.
Note that we can simulate the current api behavior by getting the BlogPost object
before :
>>> BlogPost = con.mongokit.tutorial.BlogPost
>>> blogpost = BlogPost()
>>> blogpost2 = BlogPost()
Another advantage is the ability of using the collection dynamically without pain.
Let's say that we want to put all BlogPost into a user collection (so one collection
by user) :
>>> user_col = 'me'
>>> blogpost = con.mongokit[user_col].BlogPost()
Quering is as simple as instantiating an object. There are two ways of fetching objects :
* getting raw data (the pymongo's way)
* getting instanciated object with all method defined (the mongokit way)
The first approach will produce only Python dict and is very fast.
The second will wrap the data into the MongoDocument. This is useful if we have defined
methods and want to use them.
Getting raw data :
>>> raw_data = con.mongokit.tutorial.find()
Actually, all pymongo's methods can be applied :
>>> con.mongokit.tutorial.remove({})
>>> con.mongokit.drop_collection('tutorial')
Getting instantiated objects:
>>> blogpost_cursor = con.mongokit.tutorial.BlogPost.find()
>>> bp = blogpost_cursor.next()
We can apply MongoDocument methods (`validate`, `to_json` etc...)
>>> bp.validate()
>>> bp
{'body': u'a body', 'title': u'my title', 'date_creation': datetime.datetime(...), 'rank': 0, 'author': u'me'}
Other MongoKit query methods are also available :
>>> blogpost_cursor = con.mongokit.tutorial.BlogPost.fetch() # get only BlogPost