1.Pymongo installation
安装pymongo:
pip install pymongo
- PyMongo is the driver, so that the program can be used python Mongodb database, written in python;
2.Pymongo method
insert_one()
: Inserting a record;insert()
: Inserting a plurality of records;find_one()
: Query a record, without any parameters returns the first record, with parameters press criteria to return;find()
: Query multiple records, with no parameters returns all records, with parameters according to criteria to return;count()
: View the total number of records;create_index()
: Create an index;update_one()
: Updated to match the first data;update()
: Update all data to match;remove()
: Delete a record, with no parameters means to delete all records, with participation by means drop condition;delete_one()
: Delete a single record;delete_many()
: Delete multiple records;
The operation 3.Pymongo
- View database
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456")
connect = MongoClient('mongodb://localhost:27017/', username="root", password="123456") print(connect.list_database_names())
- Access to the database instance
test_db = connect['test']
- Examples of acquired collection
collection = test_db['students']
- Insert document row, row query document, the document's line takes a value
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 构建document document = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.now()} # 插入document one_insert = collection.insert_one(document=document) print(one_insert.inserted_id) # 通过条件过滤出一条document one_result = collection.find_one({"author": "Mike"}) # 解析document字段 print(one_result, type(one_result)) print(one_result['_id']) print(one_result['author']) 注意:如果需要通过id查询一行document,需要将id包装为ObjectId类的实例对象 from bson.objectid import ObjectId collection.find_one({'_id': ObjectId('5c2b18dedea5818bbd73b94c')})
- Insert multiple rows documents, multi-line query document, see how many rows document collections
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] documents = [{"author": "Mike","text": "Another post!","tags": ["bulk", "insert"], "date": datetime(2009, 11, 12, 11, 14)}, {"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime(2009, 11, 10, 10, 45)}] collection.insert_many(documents=documents) # 通过条件过滤出多条document documents = collection.find({"author": "Mike"}) # 解析document字段 print(documents, type(documents)) print('*'*300) for document in documents: print(document) print('*'*300) result = collection.count_documents({'author': 'Mike'}) print(result)
- Compare range query
from pymongo import MongoClient
from datetime import datetime
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 通过条件过滤时间小于datetime(2019, 1,1,15,40,3) 的document documents = collection.find({"date": {"$lt": datetime(2019, 1,1,15,40,3)}}).sort('date') # 解析document字段 print(documents, type(documents)) print('*'*300) for document in documents: print(document)
- Creating an index
from pymongo import MongoClient
import pymongo
from datetime import datetime connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] # 创建字段索引 collection.create_index(keys=[("name", pymongo.DESCENDING)], unique=True) # 查询索引 result = sorted(list(collection.index_information())) print(result)
- document modification
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] result = collection.update({'name': 'robby'}, {'$set': {"name": "Petter"}}) print(result) 注意:还有update_many()方法
- Delete document
from pymongo import MongoClient
connect = MongoClient(host='localhost', port=27017, username="root", password="123456",) # 获取db test_db = connect['test'] # 获取collection collection = test_db['students'] result = collection.delete_one({'name': 'Petter'}) print(result.deleted_count) 注意:还有delete_many()方法
4.MongoDB ODM Detailed
- MongoDB ODM using a method analogous to Django ORM;
- MongoEngine mapper is a target document, written in Python, MongoDB for processing;
- Abstract MongoEngine provides is class-based, like all models are created;
# 安装mongoengine
pip install mongoengine
- Field of the type used mongoengine
BinaryField
BooleanField
ComplexDateTimeField
DateTimeField
DecimalField
DictField
DynamicField
EmailField
EmbeddedDocumentField
EmbeddedDocumentListField
FileField
FloatField
GenericEmbeddedDocumentField
GenericReferenceField
GenericLazyReferenceField
GeoPointField
ImageField
IntField
ListField:可以将自定义的文档类型嵌套
MapField
ObjectIdField
ReferenceField
LazyReferenceField
SequenceField
SortedListField
StringField
URLField
UUIDField
PointField
LineStringField
PolygonField
MultiPointField
MultiLineStringField
MultiPolygonField
5. Create a database connection using mongoengine
from mongoengine import connect
conn = connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin')
print(conn)
connect(db = None,alias ='default',** kwargs );
db
: Name of the database to be used for compatibility with connect;host
: Host name mongod instance you want to connect;port
: Port run mongod instance;username
: Used to authenticate the user name;password
: For password authentication;authentication_source
: To authenticate database;
Construction of model documents, insert data
from mongoengine import connect, \
Document, \
StringField,\
IntField, \ FloatField,\ ListField, \ EmbeddedDocumentField,\ DateTimeField, \ EmbeddedDocument from datetime import datetime # 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') math_score = Score(name='math', value=94) chinese_score = Score(name='chinese', value=100) python_score = Score(name='python', value=99) for i in range(10): students = Students(name='robby{}'.format(i), age=int('{}'.format(i)), hobby='read', gender='M', score=[math_score, chinese_score, python_score]) students.save()
Query data
from mongoengine import connect, \
Document, \
StringField,\
IntField, \
FloatField,\
ListField, \
EmbeddedDocumentField,\
DateTimeField, \
EmbeddedDocument
from datetime import datetime
# 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') first_document = Students.objects.first() all_document = Students.objects.all() # 如果只有一条,也可以使用get specific_document = Students.objects.filter(name='robby3') print(first_document.name, first_document.age, first_document.time) for document in all_document: print(document.name) for document in specific_document: print(document.name, document.age)
Modify, update, delete data
from mongoengine import connect, \
Document, \
StringField,\
IntField, \ FloatField,\ ListField, \ EmbeddedDocumentField,\ DateTimeField, \ EmbeddedDocument from datetime import datetime # 嵌套文档 class Score(EmbeddedDocument): name = StringField(max_length=50, required=True) value = FloatField(required=True) class Students(Document): choice = (('F', 'female'), ('M', 'male'),) name = StringField(max_length=100, required=True, unique=True) age = IntField(required=True) hobby = StringField(max_length=100, required=True, ) gender = StringField(choices=choice, required=True) # 这里使用到了嵌套文档,这个列表中的每一个元素都是一个字典,因此使用嵌套类型的字段 score = ListField(EmbeddedDocumentField(Score)) time = DateTimeField(default=datetime.now()) if __name__ == '__main__': connect(db='test', host='localhost', port=27017, username='root', password='123456', authentication_source='admin') specific_document = Students.objects.filter(name='robby3') specific_document.update(set__age=100) specific_document.update_one(set__age=100) for document in specific_document: document.name = 'ROBBY100' document.save() for document in specific_document: document.delete()
all()
: Return all documents;all_fields()
: Includes all fields;as_pymongo()
: Document instance but not returned pymongo value;average()
: Average value exceeds a specified value of the field;batch_size()
: Limiting the number of documents returned by a single batch;clone()
: Creates a copy of the current query set;comment()
: Add comments in the query;count()
: Calculate the selected element in the query;create()
: Create a new object, return to save the object instance;delete()
: Delete query matching documents;distinct()
: Returns the field value different lists;
Embedded document query method
count()
: The number of embedded documents in the list, the length of the list;create()
: Create a new embedded document and save it to the database;delete()
: Deleted from the database embedded in the document;exclude(** kwargs )
: To filter the list by using the given keyword arguments to exclude embedded document;first()
: Back in the first embedded documents;get()
: Embedded document retrieval determined by a given keyword arguments;save()
: Save ancestors document;update()
: Replacing the given value updating embedded document;