如何使用python本地连接到Mongo数据库

时间:2014-03-03 05:17:55

标签: python mongodb ipython pymongo

我正在使用ipython 2.7。我在mongodb中创建数据库名称enron。我尝试在本地连接到此数据库,但发生了以下错误 - 如何解决?

这是我的代码:

import json
import pymongo  # pip install pymongo
from bson import json_util 
from pymongo import MongoClient# Comes with pymongo
conn = pymongo.Connection('mongodb://user:user123@localhost27017.mongolab.com:33499/enron')
client = MongoClient()

错误:

ConnectionFailure: could not connect to localhost:27017: [Errno 10061] No connection     could be made because the target machine actively refused it

6 个答案:

答案 0 :(得分:3)

以下是创建连接和查询的命令

from pymongo import MongoClient
client = MongoClient('hostname', 27017)
db = client.database_name
collection = db.collection_name
collection.find_one({"name":"name1"})

答案 1 :(得分:1)

请参阅此PyMongo Connection以进行连接,并将连接deprecated

答案 2 :(得分:1)

from pymongo import MongoClient
from bson import json_util


MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
DB_NAME = 'Your DB name'
COLLECTION_NAME = 'collectionname'

@app.route("/")
def getDatas():
    connection = MongoClient(MONGODB_HOST, MONGODB_PORT)
    collection = connection[DB_NAME][COLLECTION_NAME]
    projects = collection.find()
    json_projects = []
    for project in projects:
        json_projects.append(project)
    json_projects = json.dumps(json_projects, default=json_util.default)
    connection.close()
    return json_projects

if __name__ == "__main__":
    app.run(host='0.0.0.0',port=5000,debug=True)

答案 3 :(得分:0)

在mongo installtion目录中从命令行运行此命令。

...>蒙戈> ...&GT箱位GT;

mongod --dbpath data / db(这里data / db是数据库的路径)

答案 4 :(得分:0)

#!pip install pymysql

import pymysql

pymysql.install_as_MySQLdb()

import MySQLdb

#!pip install pymongo
import pymongo
import json
from pymongo import MongoClient


import pandas as pd
from pymongo import MongoClient
# if __name__ == '__main__':
#     client = MongoClient("localhost", 27017, maxPoolSize=50)
client = MongoClient("localhost", 27017, maxPoolSize=50)
db = client.mydb
collection = db.angel
data = pd.DataFrame(list(collection.find()))

data

'''
Address City    Name    State   ZIP _id
0   123 Main St Whereverville   Jane Doe    CA  90210   5af03bfa8ca570abf4a2f76c
1   555 Broadway Ave    New York    John Doe    NY  10010   5af03bfa8ca570abf4a2f76d
'''

答案 5 :(得分:0)

上面@amit的派生,我用它来快速测试mongodb连接:

# pip install pymongo
from pymongo import MongoClient
client = MongoClient('mongodb://user:password@host:port/database')

for db in client.list_databases():
    print(db)