python操作MongoDB

  • SQL术语/概念MongoDB术语/概念解释/说明
    database database 数据库
    table collection 数据库表/集合
    row document 数据记录行/文档
    column field 数据字段/域
    index index 索引
    table joins   表连接,MongoDB不支持
    primary key primary key 主键,MongoDB自动将_id字段设置为主键
  • 安装pymongo库

pip install pymongo
easy_install install pymongo

 

 

  • 使用pymongo模块连接mongoDB数据库
#建立MongoDB数据库连接
from pymongo import MongoClient
client = MongoClient('localhost',27017)

#连接test数据库,没有则自动创建
db = client.test

#连接集合collection,相当于mysql的表。test为collection表名
collection = db.test

 



collection.insert()
collection.save()

(insert插入一个列表多条数据不用遍历,效率高, save需要遍历列表,一个个插入)
collection.insert({"id":1,"name":'Tom',"age":20,"gender":"female"})
collection.save({"id":2,"name":'Jack',"age":25,"gender":"male"})
#批量添加
users = [{"id":3,"name":'Lucy',"age":18,"gender":"female"},
{"id":1,"name":'Peter',"age":30,"gender":"male"}]
collection.insert(users)
View Code

 

collection.remove()
collection.remove(
<query>, #(可选)删除的文档的条件
{
justOne: <boolean>, #(可选)如果设为 true1,则只删除一个文档
writeConcern: <document> #(可选)抛出异常的级别
}
)

 

collection.update()
collection.update(
<query>, #查询条件
<update>, #update的对象和一些更新的操作符
{
upsert: <boolean>, #如果不存在update的记录,是否插入
multi: <boolean>, #可选,mongodb 默认是false,只更新找到的第一条记录
writeConcern: <document> #可选,抛出异常的级别。
}
)
collection.update({"name":"Tom"},{"$set":{"name":"Tonye"}})
注意:不加
"$set"会将其他列删除
 

 




collection.find()
collection.find_one()

(查询不到则返回None)
#查询全部 collection.find()
for i in collection.find():
  print(i)

 

  • mongodb的条件操作符
    • # (>) 大于 - $gt
    • # (<) 小于 - $lt
    • # (>=) 大于等于 - $gte
    • # (<= ) 小于等于 - $lte
  • type(判断类型)
collection.find({'name':{'$type':2}})
collection.find({'age':{'$gt':20}})

 

  • 排序
在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。    
for i in collection.find().sort([("filed",1)]):
print(i)

 

posted @ 2018-10-08 13:06  来看看博客  阅读(694)  评论(0)    收藏  举报