IT序号网

pymongo方法详解

qq123 2021年05月25日 编程语言 324 0

1.连接mongodb

#########  方法一  ########## 
import pymongo 
# MongoClient()返回一个mongodb的连接对象client 
client = pymongo.MongoClient(host="localhost",port=27017) 
 
#########  方法二  ########## 
import pymongo 
# MongoClient的第一个参数host还可以直接传MongoDB的连接字符串,以mongodb开头 
client = pymongo.MongoClient(host="mongodb://127.0.0.1:27017/")

2.指定数据库

######  方法一  ###### 
# 指定test数据库 
db = client.test 
 
######  方法二  ###### 
# 指定test数据库(调用client的test属性即可返回test数据库) 
db = client["test"]

3.指定集合

######  方法一  ###### 
# 指定student集合 
collection = db.student 
 
######  方法二  ###### 
# 指定student集合 
collection = db["student"]

4.插入数据

  • db.collection.insert()
    可以插入一条数据(dict),也可以插入多条数据(list),返回‘_id’或‘_id’的集合
###### 插入一条数据 ###### 
student = { 
 'name': 'Jordan', 
 'age': 18, 
 'gender': 'man' 
} 
 
result = db.collection.insert(student) 
# insert()返回执行后文档的主键'_id'的值 
print(result)  # 5932a68615c2606814c91f3d 
 
 
######  插入多条数据  ###### 
student1 = { 
 'name': 'Jordan', 
 'age': 10, 
 'gender': 'man' 
} 
 
student2 = { 
 'name': 'Mike', 
 'age': 11, 
 'gender': 'man' 
} 
 
result = collection.insert([student1,student2]) 
# insert()返回执行后文档的主键'_id'的集合 
print(result)  #[ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

pymongo 3.x版本中,insert()方法官方已不推荐使用,推荐使用insert_one()insert_many()将插入单条和多条记录分开。

  • db.collection.insert_one()
    用于插入单条记录,返回的是InsertOneResult对象
student = { 
 'name': 'Jordan', 
 'age': 18, 
 'gender': 'man' 
} 
 
result = collection.insert_one(student) 
# insert_one()返回的是InsertOneResult对象,我们可以调用其inserted_id属性获取_id。 
print(result)  # <pymongo.results.InsertOneResult object at 0x10d68b558> 
print(result.inserted_id) # 5932ab0f15c2606f0c1cf6c5
  • db.collection.insert_many()
    用于插入多条记录,返回的是InsertManyResult对象
student1 = { 
 'name': 'Jordan', 
 'age': 10, 
 'gender': 'man' 
} 
 
student2 = { 
 'name': 'Mike', 
 'age': 11, 
 'gender': 'man' 
} 
 
result = collection.insert_many([student1, student2]) 
# insert_many()方法返回的类型是InsertManyResult,调用inserted_ids属性可以获取插入数据的_id列表 
print(result)  # <pymongo.results.InsertManyResult object at 0x101dea558> 
print(result.inserted_ids) # [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

5.查询数据:find_one()、find()

  • db.collection.find_one()
    查询返回单个结果(dict或者None)
result = db.collection.find_one({"name": "Mike"}) 
print(result) #{'_id': ObjectId('5932a80115c2606a59e8a049'),'name': 'Mike', 'age': 21, 'gende' :'man'} 
 
db.collection.find() 
查询返回多个结果(cursor类型,可迭代)。 
results = collection.find({"age":18}) 
print(results) # <pymongo.cursor.Cursor object at 0x1032d5128> 
for result in results: 
      print(result) 
#
  • 查询条件

 
  • 多条件查询 $and $or
# and查询 
db.collection.find({  
         $and :  [ 
                { "age" :  {$gt : 10 }} ,  
                { "gender" :  "man" } 
          ] 
}) 
 
#or查询 
db.collection.find({ 
          $or : [  
                    {"age" :  {$gt : 10 }},  
                    { "gender" :  "man"} 
         ] 
}) 
 
#and查询 和 or查询 
db.inventory.find( { 
    $and : [ 
        { $or : [ { price : 0.99 }, { price : 1.99 } ] }, 
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } 
    ] 
} ) 
  • count()
    计数,对查询结果进行个数统计
count = collection.find().count() 
print(count)
  • 排序 sort()
    调用sort方法,传入要排序的字段and升降序标志即可
#单列升序排列 
results = db.collection.find().sort('name', pymongo.ASCENDING) # 升序(默认) 
print([result['name'] for result in results]) 
 
# 单列降序排列 
results = db.collection.find().sort("name",pymongo.DESCENDING)  #降序 
print([result['name'] for result in results]) 
 
#多列排序 
results = db.collection.find().sort([ 
  ("name", pymongo.ASCENDING),("age", pymongo.DESCENDING) 
])
  • 偏移 skip()
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) 
print([result['name'] for result in results])

注意:在数据量非常庞大时(千万、亿级别),最好不要用skip()来查询数据,可能导致内存溢出。可以使用
find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})
这样的方法来查询。

  • 限制 limit()
results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2) 
print([result['name'] for result in results])

6.更新数据

  • db.collection.update()
    修改单条或者多条文档,已不推荐此用法
result = collection.update( 
            {"age": {"$lt" : 15}} ,  
            {"$set" : {"gender" : "woman"}} 
) 
 
print(result)  # {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}
  • db.collection.update_one()
    修改单条文档,返回结果是UpdateResult类型

针对UpdateResult类型数据,可以调用matched_count和modified_count属性分别获取匹配的条数和影响的条数

result = db.collection.update_one( 
              {"name" : "Mike"} ,  
              { 
                "$inc" : {"age" : 5},  
                "$set": {"gender": "male"} 
              } 
) 
 
print(result)   # <pymongo.results.UpdateResult object at 0x10d17b678> 
 
print(result.matched_count, result.modified_count)   # 1  1
  • db.collection.update_many()
    修改多条文档,返回结果是UpdateResult类型
result = db.collection.update_many( 
              {"name" : "Mike"} ,  
              {"$inc" : {"age" : 5}} 
) 
 
print(result)   # <pymongo.results.UpdateResult object at 0x10c6384c8> 
 
print(result.matched_count, result.modified_count)   # 3   3

7.删除数据

  • db.collection.remove()
    删除指定条件的所有数据
result = db.collection.remove({"age" : {"$gte" : 10}}) 
 
print(result)  # {'ok': 3, 'n': 3}
  • db.collection.delete_one()
    删除第一条符合条件的数据,返回DeleteResult类型数据
result = collection.delete_one({'name': 'Kevin'}) 
print(result) # <pymongo.results.DeleteResult object at 0x10e6ba4c8> 
print(result.deleted_count)  # 1
  • db.collection.delete_many()
    删除所有符合条件的数据,返回DeleteResult类型数据
result = collection.delete_many({'name': 'Kevin'}) 
print(result) # <pymongo.results.DeleteResult object at 0x55e6be5f1> 
print(result.deleted_count)  # 4

另外,pymongo还提供了更多方法,如find_one_and_delete() find_one_and_replace() find_one_and_update(),当然,还有操作索引的方法:create_index() create_indexes() drop_index()等。

import pymongo 
 
client = pymongo.MongoClient(host="127.0.0.1", port="27017") 
 
db = client["test"] 
coll = db["myindex"] 
 
# 在后台创建唯一索引 
coll.create_index([(x,1)], unique = True, background = True,name = "x_1") 
 
# 查看集合coll的所有索引信息 
result = coll.index_information() 
print(result) 
 
# 在后台创建复合索引 
db.myindex.create_index([("x", 1), ("y", 1)]) 
 
# 删除索引 
coll.drop_index([("x", 1)]) 
# coll.drop_index("x_1")

详细用法可以参见官方文档:IT虾米网

另外还有对数据库、集合本身以及其他的一些操作,在这不再一一讲解,可以参见官方文档:IT虾米网


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

爬虫解析库:XPath