-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain_mongoengine.py
71 lines (56 loc) · 1.71 KB
/
main_mongoengine.py
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
# -*- coding: utf-8 -*-
"""CRUD - Python - MongoEngine - MongoDB."""
from mongoengine import Document, IntField, StringField, connect
db = connect(
username='dbuser',
password='123456',
host='localhost',
port=27017,
db='database_name',
authentication_source='admin',
)
# username = 'dbuser'
# password = '123456'
# host = 'localhost'
# port = 27017
# db = 'database_name'
# authentication_source = 'admin'
# URI = f'mongodb://{username}:{password}@{host}:{port}/{db}?authSource={authentication_source}'
# db = connect(host=URI)
class CollectionName(Document):
name = StringField(max_length=32)
age = IntField(min_value=0, max_value=150)
meta = {'collection': 'collection_name'}
def __str__(self):
return f'name={self.name}, age={self.age}'
if __name__ == '__main__':
CollectionName.drop_collection()
# Create.
print('[!] Create [!]')
user = CollectionName(name='renato', age=35).save()
obj_id = user.id
# Bulk create.
CollectionName.objects.insert(
[
CollectionName(name='Helena', age=20),
CollectionName(name='João', age=50),
],
)
# Read.
print('\n[!] Read [!]')
print(CollectionName.objects)
print(CollectionName.objects(id=obj_id))
print(CollectionName.objects(age__gt=20))
# Update.
print('\n[!] Update [!]')
print(CollectionName.objects(id=obj_id))
CollectionName.objects(id=obj_id).update_one(
name='joão',
)
print(CollectionName.objects(id=obj_id))
# Delete.
print('\n[!] Delete [!]')
print(CollectionName.objects(id=obj_id))
CollectionName.objects(id=obj_id).first().delete()
print(CollectionName.objects(id=obj_id))
db.close()