pymongo.Connection 用法详解
Posted 「已注销」
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pymongo.Connection 用法详解相关的知识,希望对你有一定的参考价值。
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()
‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’
Making a Connection with MongoClient (通过 MongoClient 建立连接)
The first step when working with PyMongo is to create a MongoClient to the running mongod instance. 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 independent databases . 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, 集合?不懂怎么翻译)
A 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
。。。
以上是关于pymongo.Connection 用法详解的主要内容,如果未能解决你的问题,请参考以下文章