假设我有一个BlogPost
包含零到多嵌入式Comment
文档的模型.我可以查询并让MongoDB 只 返回Comment
与我的查询规范匹配的对象吗?
例如,db.blog_posts.find({"comment.submitter": "some_name"})
仅返回评论列表.
编辑:一个例子:
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'])
在这个例子中,episode
是:
{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'}]}
但我只是想:
{u'desc': u'...', u'title': u'Episode 1'}
H.D... 7
我想你想要的是:
print db.dvds.aggregate([ {"$unwind": "$episodes"}, # One document per episode {"$match": {"episodes.title": "Episode 1"} }, # Selects (filters) {"$group": {"_id": "$_id", # Put documents together again "episodes": {"$push": "$episodes"}, "title": {"$first": "$title"} # Just take any title } }, ])["result"]
输出(除了空格)是:
[ { u'episodes': [ { u'title': u'Episode 1', u'desc': u'...' } ], u'_id': ObjectId('51542645a0c6dc4da77a65b6'), u'title': u'The Hitchhikers Guide to the Galaxy' } ]
如果你想摆脱它u"_id"
,附加管道:
{"$project": {"_id": 0, "episodes": "$episodes", "title": "$title"} }
Stephen Curr.. 6
在Mongo DB Google Groups页面上询问了同样的问题.显然它目前不可能,但计划在未来.
http://groups.google.com/group/mongodb-user/browse_thread/thread/4e6f5a0bac1abccc#
我想你想要的是:
print db.dvds.aggregate([ {"$unwind": "$episodes"}, # One document per episode {"$match": {"episodes.title": "Episode 1"} }, # Selects (filters) {"$group": {"_id": "$_id", # Put documents together again "episodes": {"$push": "$episodes"}, "title": {"$first": "$title"} # Just take any title } }, ])["result"]
输出(除了空格)是:
[ { u'episodes': [ { u'title': u'Episode 1', u'desc': u'...' } ], u'_id': ObjectId('51542645a0c6dc4da77a65b6'), u'title': u'The Hitchhikers Guide to the Galaxy' } ]
如果你想摆脱它u"_id"
,附加管道:
{"$project": {"_id": 0, "episodes": "$episodes", "title": "$title"} }
在Mongo DB Google Groups页面上询问了同样的问题.显然它目前不可能,但计划在未来.
http://groups.google.com/group/mongodb-user/browse_thread/thread/4e6f5a0bac1abccc#