import pymongo
# 总数据库
myClient = pymongo.MongoClient()
# 子数据库
myDB = myClient['DBName']
# 集合
myCollection = myDB['collectionName']
插入一条数据:insert_one
data = {
'name': 'Tom',
'age': 5
}
result = myCollection.insert_one(data)
insertId = result.inserted_id
插入多条数据:insert_many
data = [
{
'name': 'Tom',
'age': 5
},
{
'name': 'Jerry',
'age': 4
}
]
result = myCollection.insert_many(mylist)
insertIds = result.inserted_ids
查询一条数据:find_one(),返回多条数据:find()
documents = myCollection.find()
for document in documents:
print(document)
# 字段相符
myCollection.find({'age': 4, 'name': 'Tom'})
# 嵌入字段相符
# 比如有一个属性 address,其值也是一个字典,含有 zipcode 和 street
# 我们只想筛选某一个 zipcode
myCollection.find({'address.zipcode': '10075'})
# 大于操作符 $gt、小于操作符 $lt
myCollection.find({'grades.score': {'$lt': 10}})
# 第一个字母 ASCII 值大于 H
myCollection.find({'name': {'$gt': 'H' }})
# 或逻辑 $or
myCollection.find({'$or': [{'cuisine': 'Italian'}, {'zipcode': '10075'}]})
# 正则表达式 $regex
myCollection.find{'name': {'$regex': '^R'}}
结果排序:sort()
myCollection.find().sort([
("borough", pymongo.ASCENDING),
("address.zipcode", pymongo.ASCENDING)
])
限制返回条数:limit()
myCollection.find().limit(3)
更新一条数据:update_one(),更新多条数据:update_many()
result = myCollection.update_many(
{"address.zipcode": "10016", "cuisine": "Other"},
{
"$set": {"cuisine": "Category To Be Determined"},
"$currentDate": {"lastModified": True}
}
)
# 符合条件的文档数目
print(result.matched_count)
# 被修改的文档数目
print(result.modified_count)
删除一条数据:delete_one(),删除多条数据:delete_many()
result = myCollection.delete_many({"borough": "Manhattan"})
# 删除数量
print(result.deleted_count)
删除一个集合:drop()
myCollection.drop()
cursor = myCollection.aggregate(
[
{"$group": {"_id": "$borough", "count": {"$sum": 1}}}
]
)
cursor = myCollection.aggregate(
[
{"$match": {"borough": "Queens", "cuisine": "Brazilian"}},
{"$group": {"_id": "$address.zipcode", "count": {"$sum": 1}}}
]
)
本文章使用limfx的vsocde插件快速发布