2015-04-23 107 views
3

我試圖刪除一堆具有共同屬性的文檔。這是文檔的樣子:使用golang的部分屬性的mgo找不到文檔

{ 
    _id : { 
     attr1 : 'foo', 
     attr2 : 'bar' 
    }, 
    attr3 : 'baz', 
} 

多個文檔在attr1條目中具有相同的'foo'值。我試圖刪除所有這些。爲此,我已經得到了一些與此類似:

type DocId struct { 
    Attr1 string `bson:"attr1,omitempty"` 
    Attr2 string `bson:"attr2,omitempty"` 
} 

type Doc struct { 
    Id DocId `bson:"_id,omitempty"` 
    Attr3 string `bson:"attr3,omitempty"` 
} 


doc := Doc{ 
    Id : DocId{ Attr1 : 'foo' }, 
} 

collection := session.DB("db").C("collection") 
collection.Remove(doc) 

這裏的問題是,我在刪除呼叫得到一個Not found錯誤。 你能看到代碼中有什麼奇怪的東西嗎?

非常感謝!

+0

好吧,我在代碼中看到的一件奇怪的事情是它不能編譯,因爲''foo''導致語法錯誤。 – rightfold

+0

'Not found'可能是拼寫錯誤的集合名稱,或者您沒有任何與條件匹配的文檔(例如拼寫錯誤的屬性值,或者您已經刪除了所有符合條件的文檔)。你能證實這些不是這種情況嗎? – icza

+0

@rightfold,你可以猜到,這只是一個你不需要執行的例子;) – ThisIsErico

回答

1

這只是MongoDB處理完全匹配和部分匹配的結果。它可以通過蒙戈外殼被迅速證明:

# Here are my documents 
> db.docs.find() 
{ "_id" : { "attr1" : "one", "attr2" : "two" }, "attr3" : "three" } 
{ "_id" : { "attr1" : "four", "attr2" : "five" }, "attr3" : "six" } 
{ "_id" : { "attr1" : "seven", "attr2" : "eight" }, "attr3" : "nine" } 

# Test an exact match: it works fine 
> db.docs.find({_id:{attr1:"one",attr2:"two"}}) 
{ "_id" : { "attr1" : "one", "attr2" : "two" }, "attr3" : "three" } 

# Now let's remove attr2 from the query: nothing matches anymore, 
# because MongoDB still thinks the query requires an exact match 
> db.docs.find({_id:{attr1:"one"}}) 
... nothing returns ... 

# And this is the proper way to query with a partial match: it now works fine. 
> db.docs.find({"_id.attr1":"one"}) 
{ "_id" : { "attr1" : "one", "attr2" : "two" }, "attr3" : "three" } 

你會發現關於這個主題的documentation更多信息。

在你的圍棋程序,我會建議使用以下行:

err = collection.Remove(bson.M{"_id.attr1": "foo"}) 

不要忘記每一個往返到MongoDB中之後測試誤差。

+0

感謝Didier。我知道mongo中的匹配,這就是我在控制檯上查詢我的文檔的方式。疑問是我需要使用mgo編寫該行爲。 按照你的意思,我最好開始使用bson.M表示法。再一次,非常感謝! – ThisIsErico