Programmer
Programmer

Reputation: 8717

MongoDB : select * from tablename

I am new to MongoDB and need to query a table for all fields.

So I have my code as mentioned below:

dataset = db.collection.find({})
for d in dataset:
     print d

Output:

{u'_id': ObjectId('570be40a30b147fbba6f523b'), u'type': u'min_hits', u'value': u'100'}
{u'data': [u'remote', u'temprary', u'ipnodes'], u'_id': ObjectId('570be47d30b147fbba6f523c'), u'type': u'box_list'}

How can I get the values of columns

min_hits and box_list

I tried the below way

 print d['min_hits']

but I get below error:

    print d['min_hits']
KeyError: 'min_hits'

Upvotes: 0

Views: 82

Answers (1)

alecxe
alecxe

Reputation: 474001

It sounds like you should have just queried them separately using find_one():

min_hits = db.collection.find_one({"type": "min_hits"})["value"]
box_list = db.collection.find_one({"type": "box_list"})["data"]

Or, you may also meant to get the type and value or data:

dataset = db.collection.find({})
for d in dataset:
     data_type = d["type"]
     data_value = d.get("value", d.get("data", "No value or data set"))

     print(data_type, data_value)

Upvotes: 1

Related Questions