donglu6303 2015-04-23 07:38
浏览 55
已采纳

无法使用具有部分属性的golang的mgo查找文档

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!

  • 写回答

1条回答 默认 最新

  • dongtan5555 2015-04-23 10:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?