MongoDB学习笔记2:pymongo基础知识

1. 安装

安装python-dev:

sudo apt-get install python-dev
安装pip:
easy_install pip==1.2.1
安装pymongo:
sudo pip install pymongo

安装资料来自网站:

http://www.pythoner.com/259.html

2.基本使用

创建连接

>>> import pymongo
>>> connection = pymongo.Connection("localhost", 27017)
切换数据库:
>>> db = connection.test_database
获取collection:
>>> collection = db.test_collection
插入数据:
>>> collection.insert({"foo" : "bar"})
ObjectId('55063e27491ea7732d0c6def')
>>> list(collection.find())
[{u'_id': ObjectId('55063e27491ea7732d0c6def'), u'foo': u'bar'}]
批量插入:
>>> new_posts = [{"author" : "mike", "text" : "another post!"}, {"author" : "eliot", "text" : "another post too!"}]
>>> collection.insert(new_posts)
[ObjectId('55063ea8491ea7732d0c6df0'), ObjectId('55063ea8491ea7732d0c6df1')]
>>> list(collection.find())
[{u'_id': ObjectId('55063e27491ea7732d0c6def'), u'foo': u'bar'}, {u'text': u'another post!', u'_id': ObjectId('55063ea8491ea7732d0c6df0'), u'author': u'mike'}, {u'text': u'another post too!', u'_id': ObjectId('55063ea8491ea7732d0c6df1'), u'author': u'eliot'}]
获取所有collection:
>>> db.collection_names()
[u'posts', u'system.indexes', u'test_collection']



你可能感兴趣的:(MongoDB学习笔记2:pymongo基础知识)