2013-03-05 65 views
1

在我的燒瓶應用:MongoDB的查詢集保存沒有做更新,只能插入

class places(db.Document): 
    meta = { 
     'collection': 'places', 
     'allow_inheritance': False, 
    } 
    name = db.StringField(max_length=200, required=True) 
    loc= db.GeoPointField(required=True) 

x = places(loc=[-87,101], name="test") 
places.save(x) 

不過,我只想插入文檔,如果是新的,否則我想更新的行。 我不確定如何使用upsert/update。

我遇到一個錯誤,告訴我在更新之前保存(我在我的燒瓶應用程序中使用mongoengine)。

回答

0

我認爲你不能這樣做。 但是你可以嘗試下一個:

首先嚐試從數據庫

place = places.objects(name="test").first() 
if place: 
    #update here 
    place.loc = [88,102] 
else: 
    #create new here 
    place = places(loc = [-87,101], name="test") 
place.save() 
+0

可以請你對我做的如何#UPDATE這裏闡述得對象。它是不是像places.update? – user1340513 2013-03-05 09:31:21

+0

如果我嘗試使用places.objects(name =「test」),則在我的燒瓶應用程序中不返回任何內容,而在mongodb中,db.places.find({name:「test」})會返回結果。請幫忙@Elephant – user1340513 2013-03-05 09:35:51

+0

哦,那是我的錯。我在我的答案中解決這個問題。 places.objects(name =「test」)。first()當然 – Elephant 2013-03-05 09:38:52