views:

532

answers:

4

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'}
A: 

The mongodb javascript shell is documented at http://www.mongodb.org/display/DOCS/dbshell+Reference

If you want to get back only specific fields of an object, you can use

db.collection.find( { }, {fieldName:true});

If, on the other hand, you are looking for objects which contain a specific field, you can sue

db.collection.find( { fieldName : { $exists : true } } );
Dominik
i've tried to clarify my question with an example in the original post. thanks.
Carson
+2  A: 

This same question was asked over on the Mongo DB Google Groups page. Apparently its not currently possible but it is planned for the future.

http://groups.google.com/group/mongodb-user/browse_thread/thread/4e6f5a0bac1abccc#

Stephen Curran
A: 

Look at db.eval:

You should do something like:

episode = connection['dvds'].eval('function(title){
  var t = db.dvds.findOne({"episodes.title" : title},{episodes:true});
  if (!t) return null;
  for (var i in t.episodes) if (t.episodes[i].title == title) return t.episodes[i];
}', "Episode 1");

so filtering of episodes will be on a server-side.

poiuyttr
A: 

mach more simple:

db['dvd'].find_one({'episodes.title': "Episode 1"},{'episodes.title': true})

Query: coll.find( criteria, fields );Get just specific fields from the object. E.g.: coll.find( {}, {name:true} );

http://www.mongodb.org/display/DOCS/dbshell+Reference

Derlok