mongoDB-pymongo-入门

1.认识mongodb

找了很多资料,很多博客已经讲mongodb的特点说的很清楚了,总的来说,它是非关系型数据库中最像关系数据库的。我主要用python,而mongodb所用的python接口叫做pymongo。安装和python接口请百度其他博客。本文主要介绍shell及python环境下的入门操作。

2.连接mongodb

def add_city(db):
  # Changes to this function will be reflected in the output.
  # All other functions are for local use only.
  # Try changing the name of the city to be inserted
  db.cities.insert({"name" : "Chicago"})

def get_city(db):
  return db.cities.find_one()

def get_db():
  # For local use
  from pymongo import MongoClient
  client = MongoClient('localhost:27017')
  # 'examples' here is the database name. It will be created if it does not exist.
  db = client.examples
  return db

def get_all_collection(db):
  return db.collection_names()

if __name__ == "__main__":
  # For local use
  db = get_db() # uncomment this line if you want to run this locally
  add_city(db)
  print get_city(db)

3.查询

在pymongo和mongo shell中,通过find,以及findOne来实现查询操作,传入的参数为一个字典,字典可以有多个key,来进行多项查询。

city = db.cities.find_one({"name": "New York", "country":"America"})
city = db.cities.find({"name": "New York", "country":"America"})

4.投影

在很多情况下,我们并不需要输出结果那么多,我们只需要记录的特定字段,那么这个时候就用到了投影,projection。

query = {"name": "New York", "country":"America"}
projection = {"_id": 0, "name": 1}
results = db.cities.find(query, projection)

5.插入一条记录

有两种方法来增加记录,第一种,在python中创建一个字典,然后把这个字典通过insert方法传入

for a in autos:
     db.myautos.insert(a) # a must be a python dictionary

使用现成的mongoimport来把json文件直接import 进入mongoimport -d examples -c=macx –file /home/angelfish/Desktop/test.json

6.范围查询

lt"," lte”, “ gt"," gte”, “$ne”就是全部的比较操作符,对应于”<”, “<=”, “>”, “>=”,”!=”

def range_query():

  query = { 'foundingDate':{'$gte':datetime(2000,1,1,0,0)}}
  return query

in all操作符,注意all的意思是全部符合才可以,in仅仅只要满足列表中的一个就可以了

def in_query():

  query = {"manufacturer":"Ford Motor Company", "assembly" :{"$in": ['Germany', 'United Kingdom', 'Japan']}}

  return query

7.更新

方法一:通过db.collection.save,这里需要注意的是,如果这条记录已经有了_id字段,那么就跟新这条记录,如果没有_id字段,那个将创建新的记录来保存这条记录

from pymongo import MongoClient
import pprint
client = MongoClient("mongodb://localhost:27017")
db = client.examples

def main()
     city = db.cities.find_one({"name": "New York", "country":"America"})
     city["isoCountryCode"] = "DEU"
     db.cities.save(city)
if __name__ == "__main__":
     main()

方法二:通过update方法,update方法有两个输入,第一个输入是匹配记录,针对匹配到的记录进行操作,第二个是输入是包含”$set”的方法,针对上面匹配到记录进行跟新值,注意如果原来就有值,则跟新成新的值,如果原来没有这个字段,则创建新的字段。

def find()
     city = db.cities.update({"name": "New York",
                           "country":"America"},
                           {"$set":{"isoCountryCode":"DEU"}
                           })

既然提到了 set unset方法,看下面代码,跟上面的 set unset,以及后面的”“,如果匹配的记录有这个字段,那么就删除它,如果没有这个字段,那么就忽略这条语句。

def find()
     city = db.cities.update({"name": "New York",
                           "country":"America"},
                           {"$unset":{"isoCountryCode":""}
                           })

注意上面用$set跟新默认都是只针对匹配到的第一条记录进行跟新,如果需要对多条记录跟新,那么就得加上参数。

def find()
     city = db.cities.update({"name": "New York",
                           "country":"America"},
                           {"$unset":{"isoCountryCode":""}
                           }, multi=True)

8.删除

删除一条记录,通过remove命令,这个命令与find命令非常类似,讲匹配到的记录删除。

db.cities.remove( { "name": { "$exitst": 0 } } )

9. 常用shell命令

1、查询本地所有数据库名称

> show dbs;

2、切换至指定数据库环境(若无指定的数据库,则创建新的库)

> use mydb;

3、查询当前库下的所有聚集集合collection(相当于table)

> show collections;

4、创建聚集集合

> db.createCollection('mycollection');

5、查询聚集集合中数据条数

> db.mycollection.count();

6、插入数据

> db.mycollection.insert({'username':'xyz_lmn','age':26,'salary':120});

往’mycollection’聚集集合中插上一条数库,name为’xyz_lmn’,age为’26’,salary为’120’

7、查询age等于26的数据

> db.mycollection.find({"age":26});

8、查询salary大于100的数据

> db.mycollection.find({salary:{$gt:100}});

9、查询age小于30,salary大于100的数据

> db.mycollection.find({age:{$lt:30}},{salary:{$gt:100}});

10、查询salary小于40或salary大于200的数据

> db.mycollection.find({$or: [{salary: {$lt:40}}, {salary: {$gt:200}}]});

11、查询指定列的数据

> db.mycollection.find({},{age:1,salary:1});

1表示显示此列的意思,也可以用true表示

12、查询username中包含’e’的数据

> db.mycollection.find({username:/e/});

13、查询以a打头的数据

> db.mycollection.find({username:/^a/});

14、查询age列数据,并去掉重复数据

> db.mycollection.distinct('age');

15、查询前10条数据

> db.mycollection.find().limit(10);

16、查询1条以后的所有数据

> db.mycollection.find().skip(1);

17、查询第一条数据

> db.mycollection.findOne();

18、查询结果集的记录数(查询salary小于40或大于100的记录数)

> db.mycollection.find({$or: [{salary: {$lt:40}}, {salary: {$gt:100}}]}).count();

19、按salary升序排序

> db.mycollection.find().sort({salary:1});

按照salary字段升序排序

20、降序

> db.mycollection.find().sort({salary:-1});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值