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 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端