2012-08-14 17 views
1

我有一個Mongodb集合,並且爲集合中的文檔創建了一個Python類。該類有一些不與文檔一起存儲的屬性和方法。我應該嘗試並存儲它們以使屬性可搜索嗎?還是應該不存儲它們並使用Python搜索對象?在Mongodb中搜索Python類方法

下面是一個例子:

# Child 
class Child: 
    def __init__(self, **kwargs): 
     self.__dict__.update(kwargs) 

    @property 
    def parent(self): 
     try: 
      return Parent(**db.Parents.find_one({'child':self._id})) 
     except: 
      return None 

# Parent 
class Parent: 
    def __init__(self, **kwargs): 
     self.__dict__.update(kwargs) 

    @property 
    def child(self): 
     try: 
      return Child(**db.Children.find_one({'parent':self._id})) 
     except: 
      return None 

在這個例子中,要搜索所有的孩子誰的父母的名字是「富」,我必須這樣做:

results = [Child(**c) for c in db.Children.find() if c.parent.name == 'foo'] 

這意味着我必須從Mongodb中提取所有的Children文檔並搜索它們。將Parent數據(或其子集)寫入Child文檔是否更智能,因此我可以使用Mongodb進行搜索?所以,我的孩子類看起來是這樣的:

# Child 
class Child: 
    def __init__(self, **kwargs): 
     self.__dict__.update(kwargs) 

    @property 
    def parent_name(self): 
     try: 
      return db.Parents.find_one({'child':self._id})['name'] 
     except: 
      return None 

    def _save(self): 
     # something like this to get and save all the properties 
     data = {m[0]:getattr(self,m[0]) for m in inspect.getmembers(self)} 
     db.Children.find_and_modify({'_id':self._id},{'$set':data},upsert=True) 

# search 
results = [Child(**c) for c in db.Children.find({'parent_name':'foo'})] 

所以搜索是更有效的,但我認爲有保持更新可能是痛苦和危險的子對象。如果我改變父母的名字,我還必須重寫孩子。感覺不對。任何更好的想法?

回答

2

您無需加載全部Children

parent_ids = db.Parents.find({'name': 'foo'}).distinct('_id') 
children = db.Children.find({'parent': {'$in': parent_ids}}) 

(另外,爲什麼你對父母一個parent場對孩子同時擁有child場?)

+0

謝謝,這是事實。父母/孩子是一個微弱的例子。在我的實際模型中沒有循環參考。再次感謝! – MFB 2012-08-14 07:02:44