Don't find documents using golang mgo with partial attributes
I am trying to delete a bunch of documents that have a common attribute. This is what the document looks like:
{
_id : {
attr1 : 'foo',
attr2 : 'bar'
},
attr3 : 'baz',
}
More than one document will have the same "foo" value in the attr1 entry. I am trying to remove all of them. For this I have something similar to this:
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)
The problem is I am getting an error Not found
in the call to remove. Do you see something strange in the code?
Thank you so much!
+3
source to share
1 answer
This is just a consequence of how MongoDB handles exact and partial matches. It can be quickly demonstrated with a mango shell:
# 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 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" }
You can find more information on this topic in the documentation .
In your Go program, I suggest using the following line:
err = collection.Remove(bson.M{"_id.attr1": "foo"})
Don't forget to check for errors after every return to MongoDB.
+1
source to share