I have a mongoDB with a collection named Movies inside the collection i stored some info like this:
I also have an html and i just want to display the title:
<h3>{{ title}}</h3>
to do that I run this code:
@app.route("/movieInfo")
def movieInfo():
title = db.db.Movies.find_one({"title": "Endgame"})
ticketDate = "10/10/20 17:00"
return render_template("movieInfo.html", title=title)
when I try that I get everything on the Collection and not the title only which i want.
instead of the title I get this: {'_id': ObjectId('5f525e1328638ac98f69c936'), 'title': 'Endgame', 'releaseDate': '26 April 2019', 'info': "After the devastating events of Avengers: Infinity War (2018), the universe is in ruins. With the help of remaining allies, the Avengers assemble once more in order to reverse Thanos' actions and restore balance to the universe.", 'ticketDate': '10/10/20 - 17:00'}
How do I store The title only?
Well, because you are getting back a dict, you can simply convert your code to be:
movie = db.db.Movies.find_one({'title': 'Endgame'})
title = movie.get('title')
Another thing you can do is specify projection
in order to get only the fields you want (which will take less bandwidth and theoretically be faster).
This would look like this:
movie = db.db.Movies.find_one({'title': 'Endgame'}, projection={'title': True, '_id': False})
title = movie.get('title')
Notice that you still get back a dict and you need to put _id
to false because by default _id is always returned.