如何映射减少mongodb中的朋友搜索

时间:2013-11-05 10:32:11

标签: python mongodb mapreduce pymongo mongoengine

我有一个朋友列表(对象ID列表)和一个搜索查询。我想搜索我的朋友,其名字首先是,就像搜索查询一样。我可以看到我需要使用map / reduce,但我不会想到如何做到这一点。

class UserAccount(Document):
    first_name = StringField(max_length = 20)
    last_name = StringField(max_length = 20)
    user_name = StringField(max_length = 20)
    email = EmailField()
    password = StringField(max_length = 20)
    friends = ListField(ReferenceField('self'))


# List Of Friends IDs
friends = [ObjectId("5278a1821d41c80d7a3ed4ec"), ObjectId("5278a1821d41c80d7a3ed4fe"), 
ObjectId("5278a1821d41c80d7a3ed4aa"), ObjectId("5278a1821d41c80d7a3ed4bb")]    

# Assume a search query. 
search_query = 'some-name'

regex = re.compile('^' + re.escape(search_query))
users = UserAccount._get_collection()
result = users.find( 
{ 
    "_id" : friends[0], 
    "first_name" : regex                    
})

是否感谢任何帮助或参考?

1 个答案:

答案 0 :(得分:1)

不需要减少地图 - 这应该找到所有匹配的朋友:

UserAccount.objects.filter(pk__in=friends, name=regex)