python 使用pymongo在python中使用MongoDB的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用pymongo在python中使用MongoDB的示例相关的知识,希望对你有一定的参考价值。

#./bin/mongod --dbpath=./data

import pymongo
cli = pymongo.MongoClient('mongodb://localhost:27017')

#drop the table
#cli.testdb.babies.drop()
import csv
with open('babynames.csv','rb') as csvfile:
    babies = csv.reader(csvfile)
    next(babies)
    for row in babies:
        cli.testdb.babies.insert({'year': row[0],
                                 'firstname':row[1],
                                 'country':row[2],
                                  'sex':row[3],
                                  'count':row[4]})
#./bin/mongod --dbpath=./data

from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
client.phonebook.collection_names()
db=client.phonebook
col=db.people

cmd=''
while(cmd!='exit'):
	cmd=raw_input("Joe: ")
	if(cmd=='show'):
		people=col.find()
		for person in people:
			print person
	elif(cmd=='insert'):
		name=raw_input("Name: ")
		phone=raw_input("Phone: ")
		node=input("Node: ")
		col.insert({'name':name,'phone':phone},w=node,j=False)	#w=0, write data asyncronous, 
	elif(cmd=='remove'):
		name=raw_input("Name: ")
		col.remove({"name": name})
	elif(cmd=='destroy'):
		col.remove()
	elif(cmd=='update')
		name=raw_input("Name: ")
		phone=raw_input("Phone: ")
		#This will replace the entry without store the last field
		#col.update({'name':name},{name'phone':phone})
		col.update({'name':name},{'$set':{'phone':phone}})
	elif(cmd!='exit'):
		print "Unknown command"

"""
	#find return a cursor, it work like a generator
	cursor=col.find()
	#return next element
	next(cursor)
	#return the cursor as a list of dict
	list(cursor)

	#advanced search query
	col.find_one({'name':'Giuseppe'},)
	#find all entries with id greater than OBJ_ID
	list(col.find({'_id':{'$gt':bson.ObjectId('OBJ_ID')}}))

	#find all entries with name that start with O using regex
	list(col.find({'name':{'$regex':'^O'}}))

	#Other way to update
	doc=col.find_one({'name':'Giuseppe'})
	doc['phone']='12345'
	col.save(doc) #or col.update({'name':'Giuseppe'},doc)
	
	#Drop a table
	#drop the table
  #client.testdb.babies.drop()

以上是关于python 使用pymongo在python中使用MongoDB的示例的主要内容,如果未能解决你的问题,请参考以下文章

使用 pymongo 将自定义 python 对象编码为 BSON

在 python/pymongo 中将 bson 转换为 json

python数据库 pymongo 的使用

python安装pymongo时出错

pymongo的使用方法

Python中的数据库连接与查询——使用pymongo