0

I am new to mongoDB and don't know more than the basics of python and i'm trying to get some data from a MongoDB database, I can get it using this code. My question is: How can I convert what comes out (I added it here) to json so that I can separate things like name, brithdate, birthday, etc.

import pymongo
myclient = pymongo.MongoClient("mongodb://10.0.0.45:27017/")

mydb = myclient["mydatabase"]

mycol = mydb["birthdays"]


myquery = { "name": "John" }
mydoc = mycol.find(myquery)

for x in mydoc:
  print(x)

This is what gets printed in the for x in mydoc:

data that I get from MongoDB: {u'birthmonth': u'<month>', u'_id': ObjectId('5db3a42431f86884b0746c3e'), u'name': u'<name>', u'birthday': u'<day>', u'birthyear': u'<year>'}

And when I just print mydoc I get

<pymongo.cursor.Cursor object at 0x10a1b4c90>

I am not actually getting the <> in the for x in mydoc: when I print, I just added them to replace the actual data.

btw I got the code from https://www.w3schools.com/python/python_mongodb_query.asp

mtz_federico
  • 107
  • 1
  • 9

1 Answers1

0

What you get by iterating from cursor is python dictionary. You dont need to convert it to json and also MongoDB is working with BSONs, what means some fields could be not JSON serializable for example field "_id". To get values you use something like this:

for x in mydoc: 
    print(x['birthmonth'],x['_id'], x['name'], :x['birthday'], x['birthyear'])

But if you really want json your code will look something like this:

import json
import pymongo

myclient = pymongo.MongoClient("mongodb://10.0.0.45:27017/")

mydb = myclient["mydatabase"]
mycol = mydb["birthdays"]
myquery = { "name": "John" }
#because ObjectId is not JSON serializable
project = {"_id":0}
mydoc = mycol.find(myquery, project)

for x in mydoc:
    print(json.dumps(x))
oktogen
  • 391
  • 2
  • 5