pymongo.Connection 用法详解

来源:互联网 发布:路由器选择算法 要求 编辑:程序博客网 时间:2024/06/05 12:48

pymongo的Connection()方法不建议使用,官方推荐新方法MongoClient() 


db = pymongo.Connection("192.168.1.2",27017)

解决:

conn = pymongo.MongoClient("localhost", 27017)

参考:


消息来源为PyMongo项目文档:http://api.mongodb.org/python/current/api/pymongo/connection.html
原文为英文,该页面讨论了Connection() 的各种具体用法,但不建议使用connection()而要用Mongo_Client()
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’

Warning
DEPRECATED: Please use mongo_client instead.
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘
关于 mongo_client,以下是节选的使用简例:

Making a Connection with MongoClient (通过 MongoClient 建立连接)
The first step when working with PyMongo is to create aMongoClient to the running mongodinstance. Doing so is easy:
(以下方法将使用当前默认的Mongo服务器)

>>> from pymongo import MongoClient>>> client = MongoClient()


The above code will connect on the default host and port. We can alsospecify the host and port explicitly, as follows:
(以下方法将使用给定主机位置和端口)

>>> client = MongoClient('localhost', 27017)

Or use the MongoDB URI format:
>>> client = MongoClient('mongodb://localhost:27017/')



Getting a Database (建立一个Mongo DB)
A single instance of MongoDB can support multiple independentdatabases. Whenworking with PyMongo you access databases using attribute style accesson MongoClient instances:
(以下位建立方法,如果DB已经存在,不会有任何影响)

>>> db = client.test_database

If your database name is such that using attribute style access won’twork (like test-database), you can use dictionary style accessinstead:
(以下方法用于DB名称存在python不支持的字符的情况)

>>> db = client['test-database']



Getting a Collection (建立一个Collection, 集合?不懂怎么翻译)
collection is agroup of documents stored in MongoDB, and can be thought of as roughlythe equivalent of a table in a relational database. Getting acollection in PyMongo works the same as getting a database:

>>> collection = db.test_collection

or (using dictionary style access):
>>> collection = db['test-collection']


An important note about collections (and databases) in MongoDB is thatthey are created lazily - none of the above commands have actuallyperformed any operations on the MongoDB server. Collections anddatabases are created when the first document is inserted into them.

以上说的是关于collection和database创建,实际发生过程并不是在语句compile之后立即发生,而是在第一次将文档(数据)存入对应的database和collection里面的时候才会发生,这就是为什么黄老师的代码里面进入生成N个新元素前要先存入一个{x:1}
。。。


原创粉丝点击