I am using pymongo driver to work with Mongodb using Python. Every time when I run a query in python shell, it returns me some output which is very difficult to understand. I have used the .pretty() option with mongo shell, which gives the output in a structured way.
I want to know whether there is any method like pretty() in pymongo, which can return output in a structured way ?
I want to know whether there is any method like pretty() in PyMongo
No PyMongo doesn't provide such method. It is only available in the shell.
You need to use the pprint function from the pprint module.
Actually you can also program it by yourself like:
db = connection.[dbname]
collection = db.[yourcollectionname]
for col in collection.find({}):
for keys in col.keys():
print ('{', keys, ":" , col[keys] , '}' )
I think this will be helpful or take it as an option.
I'm a bit new to this too but I might have found a viable answer for those who are looking. Libraries I'm using are pymongo, bson, json, from bson import json_util and from bson.json_util import dumps, loads
Where you want to print (or return) try:
print(loads(dumps(stringToPrint, indent=4, default=json_util.default)))
If your data is already using loads, you will not need loads in this statement.
If you want to use return leave out the first parentheses.
Example:
return json.loads(json.dumps(string, ..... )
If you imported loads and dumps you can leave out json..
I haven't tried (because this worked great for me) to alter the 'indent' value but if you don't like how the output looks, try changing that.
There is no direct method to print output of pymongo in a structured way.
as the output of pymongo is a dict
print(json.dumps('variable with out of pymongo query'))
this will serve your purpose i think
It probably depends on your IDE, not the pymongo itself. the pymongo is responsible for manipulating data and communicating with the mongodb. I am using Visual Studio with PTVS and I have such options provided from the Visual Studio. The PyCharm is also a good option for IDE that will allow you to watch your code variables and the JSON in a formatted structure.
Related
I have written 2 functions for mapping and one for reducing in MongoDB. When I run this command below, it returns only the results for the MapReduce Code. I would like to see the source code to make some changes.
db.mapreduce_result.find().pretty()
Thanks,
One can use toSource() to find the source code of any Javascript method.
The toSource() method returns a string representing the source code of the object.
Since mongo shell is a complete JS interpreter you can use this method.
In your case the command would be: db.mapreduce_result.find().pretty().toSource().
Example: You can see the result when I used it for db.collection.find() method:
What is the difference between:
db.getCollection('booking').find()
and
db.booking.find()
Are they exactly the same, or when should I use which one?
db.getCollection('booking').find({_id:"0J0DR"})
db.booking.find({_id:"0J0DR"})
Yes, they are exactly the same and you can use either.
The first form db.getCollection(collectionName).find() becomes handy when your collection name contains special characters that will otherwise render the other syntax redundant.
Example:
Suppose your collection has a name that begin with _ or matches a database shell method or has a space, then you can use db.getCollection("booking trips").find() or db["booking trips"].find() where doing db.booking trips.find() is impossible.
I prefer using db.collection() to either as it will work on nonexistent collections, which is particularly useful when for example creating the first user in a users collection that doesn't yet exist.
db.collection('users').findOneAndUpdate(...) // Won't throw even if the collection doesn't exist yet
In addition to the previous answers, on the shell, they might be exactly the same but in real IDE (like PyCharm), db.getCollection(collectionName) gives you back the whole doculment even with out the find() method.
In earlier versions say MongoDB 2.6, the DBCollection class has this method getStats().
DBCollection.getStats()
In the new 3.x versions , we have a new class
MongoCollection
and it has no method to get the statistics.
My question is how to get the statistics from the MongoCollection class
So I think I've found a solution for you. It's a bit hackish, but from what I was reading, I couldn't find any other way around it. I was reading resources from Mongo and they were saying they simplifed the driver a bit and reduced the amount of available methods for a collection. I would guess that getStats() probably got cut since it doesn't seem like something you would do often, at least not programmatically for most use cases anyways. So here's what you can do:
First, a MongoDatabase object will have a runCommand() method. 3.0 driver docs
If you look here, you will get a list of all the commands you can execute with runCommand().
One of those commands is collStats. Based on the documentation, it looks like you will want to pass run command a Bson object that has the following form:
{
collStats: <string>,
scale: <int>,
verbose: <boolean>
}
where the collStats is the string name of the collection for which you want stats. Scale is an optional field; you can read about it at the last link. Verbose defaults to false.
I don't know for sure that this will get you want you want, but it will at least get you pretty close. Let me know how it works out!
I've been looking into Koa.js recently as a next-gen option for running a server (looks good so far...) and came across the following code in an API example:
function *reqlogger(next){
console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
yield next;
}
Most of this code looks pretty good, but I'm not sure whether to leave toISOString() in. The first console.log parameter(s) is formatting the result as string(s) anyway, so why would I want to bother converting the string to ISO format?
Are there any additional benefits I might see down the line to declaring like this? Are there particular functions that prefer date objects in ISO format, for example, or is it just a matter of personal preference?
I'm interested in displaying recently searched terms (stored in a database) on every page of my application. At first glance, it seems like layout.html would be the best place for this function. I'd need to run database queries, and they'd look something like this:
{{import pymongo}}
{{db = pymongo.MongoClient()}}
{{result = db.collection.distinct("search_term")}}
{{etc...}}
I'm not sure it's the wisest idea. In terms of security, should I be concerned about running database queries from a view? Are there any other alternatives?
There is no security issue, as the view is executed on the server. However, a better practice would be to move that code to a model file, and then simply display the result in the layout (any objects defined in a model file will be available in the view's execution environment).
In a model file:
import pymongo
db = pymongo.MongoClient()
result = db.collection.distinct("search_term")
And then in layout.html:
{{for record in result:}}
[code to display record]
{{pass}}
Another option would be to move the code to a module and simply import and call a function in the layout (the idea is to limit the views to display-related code only, particularly since it is a little harder to read and debug Python code in the views).