MongoDB query to return only embedded document

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-02-15T20:02:49Z Indexed on 2010/05/10 4:18 UTC
Read the original article Hit count: 277

Filed under:
|
|

assume that i have a BlogPost model with zero-to-many embedded Comment documents. can i query for and have MongoDB return only Comment objects matching my query spec?

eg, db.blog_posts.find({"comment.submitter": "some_name"}) returns only a list of comments.

edit: an example:

import pymongo

connection = pymongo.Connection()
db = connection['dvds']

db['dvds'].insert({'title': "The Hitchhikers Guide to the Galaxy",
                   'episodes': [{'title': "Episode 1", 'desc': "..."},
                                {'title': "Episode 2", 'desc': "..."},
                                {'title': "Episode 3", 'desc': "..."},
                                {'title': "Episode 4", 'desc': "..."},
                                {'title': "Episode 5", 'desc': "..."},
                                {'title': "Episode 6", 'desc': "..."}]})

episode = db['dvds'].find_one({'episodes.title': "Episode 1"}, 
                              fields=['episodes'])

in this example, episode is:

{u'_id': ObjectId('...'),
 u'episodes': [{u'desc': u'...', u'title': u'Episode 1'},
               {u'desc': u'...', u'title': u'Episode 2'},
               {u'desc': u'...', u'title': u'Episode 3'},
               {u'desc': u'...', u'title': u'Episode 4'},
               {u'desc': u'...', u'title': u'Episode 5'},
               {u'desc': u'...', u'title': u'Episode 6'}]}

but i just want:

{u'desc': u'...', u'title': u'Episode 1'}

© Stack Overflow or respective owner

Related posts about mongodb

Related posts about best-practices