pymongo 使用测试

>>> import pymongo
>>> uri = "mongodb://recall:123456@oceanic.mongohq.com:10062/must"
>>> client = pymongo.MongoClient(uri)   #连接到数据库
>>> db = client.must                    #选择数据库名
>>> db.collection_names                 #查看所有聚集名,相当与show_tables
<bound method Database.collection_names of Database(MongoClient('oceanic.mongohq.com', 10062), u'must')>
>>> table = db.mytable                  #创建聚集
>>> count = table.count()               #查看聚集中的数目
>>> count
0
>>> monster = {"name":"Dracule","occupation":"Blood Suker","tags":["vampire","teeth","bat"],"data":"19981010"}
>>> insert_id = table.insert(monster)   #插入数据
>>> for monster_one in table.find():
...     print monster_one
...
...
{u'occupation': u'Blood Suker', u'_id': ObjectId('53510fcad6ca3fb153c5681d'), u'data': u'19981010', u'name': u'Dracule', u'tags': [u'vampire', u'teeth', u'bat']}
>>> print table.find_one({"name":"Dracule"})
{u'occupation': u'Blood Suker', u'_id': ObjectId('53510fcad6ca3fb153c5681d'), u'data': u'19981010', u'name': u'Dracule', u'tags': [u'vampire', u'teeth', u'bat']}

可查看 http://docs.mongohq.com/languages/python.html

import os
import datetime
import pymongo
from pymongo import MongoClient
 
# Grab our connection information from the MONGOHQ_URL environment variable
# (mongodb://linus.mongohq.com:10045 -u username -pmy_password)
MONGO_URL = os.environ.get('MONGOHQ_URL')
#connection = Connection(MONGO_URL)
client = MongoClient(MONGO_URL)
 
# Specify the database
db = client.mytestdatabase
# Print a list of collections
print db.collection_names()
 
# Specify the collection, in this case 'monsters'
collection = db.monsters
 
# Get a count of the documents in this collection
count = collection.count()
print "The number of documents you have in this collection is:", count
 
# Create a document for a monster
monster = {"name": "Dracula",
           "occupation": "Blood Sucker",
           "tags": ["vampire", "teeth", "bat"],
           "date": datetime.datetime.utcnow()
           }
 
# Insert the monster document into the monsters collection
monster_id = collection.insert(monster)
 
# Print out our monster documents
for monster in collection.find():
    print monster
 
# Query for a particular monster
print collection.find_one({"name": "Dracula"})

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值