This is my code so far:
from pymongo import MongoClient
client = MongoClient()
client = MongoClient('localhost', 27017)
db = client.local
collection = db.orderbook_update
orderbook = collection.find({
"lastUpdated": {"$lt": ts}
}).sort("position",pymongo.DESCENDING).limit(1)
print(orderbook)
When I do that, my print(orderbook) gives me that: <pymongo.cursor.Cursor object at 0x7ff7defef828>
How am I able to print my result in order to use it? My json file on my database has three main components: lastUpdated, asks, bids.
Thank you!
order = list(orderbook)
Note: Once you do do this cursor object will not be available
Related
I'm creating a collection and want to insert it in my database
I have imported pymongo and also I defined db = myClient["mydb"] this way but it says command insert requires authentication
>>> import pymongo
>>> from pymongo import MongoClient
>>> myClient = MongoClient()
>>> db = myClient.mydb
>>> users = db.users
>>> user1 = {"username": "nick", "password": "mysecurepass", "fav_num": 445}
>>> user_id = users.insert_one(user1).inserted_id
line 155, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command insert requires authentication
It looks like the MongoDB instance you are using is set up with authentication, but when you create the connection using myClient = MongoClient() you are not giving it credentials. When you connect to the database try something like this:
client = MongoClient('example.com',
username='user',
password='password')
this will pass the correct username and password to the Mongo instance and allow you to connect. use this link for some examples on how to use authentication with pymongo.
I instantiate Mongo Client as below. It works fine. However I am trying to read the DB name (primer here) from the configuration. How do I do that?
from pymongo import MongoClient
client = MongoClient()
db = client.primer # want to read "primer" string from a variable
coll = db.dataset
You could do:
db_name = 'primer'
db = getattr(client, db_name)
if you are trying to connect to only one database you can specify the dbname while creating the db object itself
dbname = "primer"
db = MongoClient()[dbname]
I would like the data to be inserted in mycollection, but it'll literally insert into a collection called 'collection' when I use the collection variable before insert_one.
client = MongoClient()
db = client['mydb']
collection = db['mycollection']
db.collection.insert_one({"id": "hello"})
I didn't realize I had to remove the db part. This worked:
collection = db['mycollection']
collection.insert_one({"id": "hello"})
In a mongo command line I can run
db.my_collection.stats()
I need to get my collections stats from Python so I tried
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
collection = db.test_collection
collection.stats()
But I get
TypeError: 'Collection' object is not callable.
If you meant to call the 'stats' method on a 'Collection' object it is failing because no such method exists.
This is because pymongo does not support this method. How do I send raw mongoDB commands to mongo through Python?
from pymongo import MongoClient
client = MongoClient()
db = client.test_database
print(db.command("collstats", "test_collection"))
Approach 1 with PyMongo:
client = pymongo.MongoClient(host = "127.0.0.1", port = 27017)
db = client.test_database
db.command("dbstats") # prints database stats for "test_db"
db.command("collstats", "test_collection") # prints collection-level stats
This can be done with this approach in Django.
from django.db import connections
database_wrapper = connections['my_db_alias']
eggs_collection = database_wrapper.get_collection('eggs')
eggs_collection.find_and_modify(...)
From django-mongodb-engine docs:
django.db.connections is a dictionary-like object that holds all
database connections – that is, for MongoDB databases,
django_mongodb_engine.base.DatabaseWrapper instances.
These instances can be used to get the PyMongo-level Connection,
Database and Collection objects.
On the command line, this works:
$ mongo
> show dbs
mydatabase 1.0GB
However, this does not:
$ python
>>> import pymongo
>>> connection = pymongo.MongoClient()
>>> connection.mydatabase.find()
I read through docs here:
http://api.mongodb.org/python/current/tutorial.html
But do not understand how to either...
connect to an existing database (using pymongo)
query what databases exist in the mongodb connection.
Why can't I access my database?
Connect to an existing database
import pymongo
from pymongo import MongoClient
connection = MongoClient()
db = connection.mydatabase
List existing databases
import pymongo
from pymongo import MongoClient
connection = MongoClient()
# connection.database_names() # depreciated
connection.list_database_names()
The question implies user has a local MongoDB. However I found this question trying to connect to a remote MongoDB. I think the tutorial is worth mentioning (no other answer here mentioned how I can specify the host and the port)
The above code will connect on the default host and port. We can also specify the host and port explicitly, as follows:
client = MongoClient('localhost', 27017)
Or use the MongoDB URI format:
client = MongoClient('mongodb://localhost:27017/')
show dbs and find() are totally different commands as such you cannot compare the two.
connection.mydatabase.find()
Will actually do nothing because you cannot find() documents on database level. You are probably looking for:
cursor = connection.mydatabase.mycol.find()
I am no Python programmer but something like that and the foreach the cursor var to get your data.
As an added note you will want to replace mycol with the collection name that contains your documents.
As for querying for a list of databases you can do something like:
databases = connection.mydatabase.command({'listDatabases': 1});
As shown here: http://docs.mongodb.org/manual/reference/command/listDatabases/#listDatabases
However again I am no Python programmer but this should get you started.
On the python command line:
import pymongo
from pymongo import MongoClient
connection = MongoClient() ## connects by default to db at localhost:27017
connection.database_names() ## python binding equivalent to show dbs.
Although there doesn't seem to be a wealth of examples, it appears that the bindings are pretty complete within the Python Driver API Documentation.
database_names() is deprecated. One can use list_database_names() instead.
mongo_db_url will be something like "mongodb://localhost:27017/". 27017 is deafult port number, replace suitably.
from pymongo import MongoClient
client = MongoClient(<mongo_db_url>)
#or client = MongoClient('localhost', 27017)
client.list_database_names()