2015-10-14 60 views
3

是否有可能使用變量作爲集合名稱的一部分並根據mongoengine中的名稱查詢不同的集合?通過mongoengine和Django中的不同變量查詢不同的集合

例如:

有我的MongoDB 3個集

  • collection_first
  • collection_second
  • collection_third

並執行一個簡單的循環,如:

collection_names = ['first', 'second', 'third'] 
for name in collection_names: 
    ## Query the collection_+`name` here 

順便說一下,我在Django中使用mongoengin,如何設置這種場景的model.py?

class Testing(DynamicDocument): 
    # The collection_name should be dynamic, isn't it? 
    meta = {'collection' : 'collection_name'}   
    user_name = StringField(db_field='user_name') 

非常感謝。


更新解決方案。

定義在models.py模型,而不元:

class Testing(DynamicDocument): 
    ## Do NOT use the meta to point to a specific collection. 
    user_name = StringField(db_field='user_name') 

當你調用該函數,使用switch_collection切換到真實採集:

def search_in_testing(self, name, **kwargs): 
    with switch_collection(Testing, 'colection_%s' % (name)): 
     search_results = Testing.objects(**kwargs) 
    return search_results 

在你的代碼,只需調用for循環中的函數:

collection_names = ['first', 'second', 'third'] 
for name in collection_names: 
    search_results = search_in_testing(name, name=name) 

參考:switch_collection in mongoengine

回答

0

是的,你可以這樣做。作爲示例,

for name in collection_names: 
    for doc in db[collection_+'name'].find(): 
     print doc 

這裏db是Database對象。

+0

你知道如何定義'model.py'在Django? –

+0

mongoengine仍然不支持django我猜。我沒有嘗試過。我會研究一下,讓你知道。 –

+0

謝謝,我在0.90之前使用,它在該版本中支持Django。 –

0

可能在這個commit下面的測試將幫助以某種方式:

def test_dynamic_collection_naming(self) 
     def create_collection_name(cls): 
      return "PERSON" 

     class DynamicPerson(Document): 
      name = StringField() 
      age = IntField() 

      meta = {'collection': create_collection_name} 

     collection = DynamicPerson._get_collection_name() 
     self.assertEquals(collection, 'PERSON') 
     DynamicPerson(name='Test User', age=30).save() 
     self.assertTrue(collection in self.db.collection_names())