Search code examples
mongodbgoattributespartialmgo

Not finding documents using golang's mgo with partial attributes


I'm trying to remove a bunch of documents that have a common attribute. This is what a 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'm trying to remove all of those. For that I've got 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 here is that I'm getting a Not found error in the remove call. Can you see anything odd in the code?

Thanks a lot!


Solution

  • This is just a consequence of the way MongoDB handles exact match and partial match. It can be quickly demonstrated using the mongo 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'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" }
    

    You will find more information about this topic in the documentation.

    In your Go program, I would suggest to use the following line:

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

    Do not forget to test errors after each roundtrip to MongoDB.