简体   繁体   中英

Pymongo iterate through list of docs

I'm a complete newbie to Stackoverflow, MongoDB, and PyMongo. I have a database with a collection called posts that looks like the following.

{
    EXPERIMENT:1,
    DATA[
        {TIMESTAMP:1/1/1000 00:00:00,
         "A":1,
         "B":2,
         "C":3
        },
        {TIMESTAMP:1/1/1000 00:00:01,
         "A":4,
         "B":5,
         "C":6
        }
    ]
}

I'm not even sure if this is the best way to model the data structure but it's what I have right now and I would like to query it. When I try the query,

db.posts.find({EXPERIMENT:1},{DATA.TIMESTAMP:1, _id:0})

I get what I want, however, I get "DATA" back which I think is a list of documents but I can't iterate through it.

for result in db.posts.find({EXPERIMENT:1},{DATA.TIMESTAMP:1, _id:0}):
    print result;

This just prints one massive thing rather than going through DATA line by line. I tried also:

for result in db.posts.find({EXPERIMENT:1},{DATA.TIMESTAMP:1, _id:0}):
    for value in result:
        print value;

I then get the result DATA, again, not something that I can iterate through. Clearly, I'm missing something fundamental. Can someone please point me in the right direction? Maybe a little off topic but do you also have book suggestions that might cover this?

Thank you!

EDIT: Ultimately, I would like a result set that looks like:

DATA = [1/1/1000 00:00:00, 1/1/1000 00:00:01]

where DATA is a traditional python list so that I can do:

for value in DATA:
    print value;
    # Do something else with data

Again, I know I'm missing something really basic. Thanks for your help and understanding!

It prints one "big thing" like this?

In [12]: for result in db.test.find({'EXPERIMENT':1}, {'DATA.TIMESTAMP':1, '_id':0}): print result
{u'DATA': [{u'TIMESTAMP': u'1/1/1000 00:00:00'}, {u'TIMESTAMP': u'1/1/1000 00:00:01'}]}

Then, you should try pprint:

In [13]: from pprint import pprint

In [14]: for result in db.test.find({'EXPERIMENT':1}, {'DATA.TIMESTAMP':1, '_id':0}): pprint(result)
{u'DATA': [{u'TIMESTAMP': u'1/1/1000 00:00:00'},
           {u'TIMESTAMP': u'1/1/1000 00:00:01'}]}

You can also do:

In [15]: for result in db.test.find({'EXPERIMENT':1}, {'DATA.TIMESTAMP':1, '_id':0}):
   ....:     for k, v in result.items():
   ....:         print k, v
   ....:         
DATA [{u'TIMESTAMP': u'1/1/1000 00:00:00'}, {u'TIMESTAMP': u'1/1/1000 00:00:01'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM