【问题标题】:Not finding documents using golang's mgo with partial attributes找不到使用具有部分属性的 golang 的 mgo 的文档
【发布时间】:2015-04-23 07:38:07
【问题描述】:

我正在尝试删除一堆具有共同属性的文档。这是一个文档的样子:

{
    _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 错误。 你能看出代码中有什么奇怪的地方吗?

非常感谢!

【问题讨论】:

  • 好吧,我在代码中看到的一件奇怪的事情是它无法编译,因为'foo' 导致语法错误。
  • Not found 可能是集合名称拼错的结果,或者您没有任何符合条件的文档(例如,您拼错了属性值,或者您已经删除了所有可能匹配它)。你能确认这些不是吗?
  • @rightfold,你可以猜到,这只是一个你不需要执行的例子;)
  • @icza,我已经检查过了。我正在查询具有匹配条件的正确集合:)

标签: mongodb go attributes partial mgo


【解决方案1】:

这只是 MongoDB 处理完全匹配和部分匹配方式的结果。可以使用 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" }

您将在documentation 中找到有关此主题的更多信息。

在您的 Go 程序中,我建议使用以下行:

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

不要忘记在每次往返 MongoDB 后测试错误。

【讨论】:

  • 非常感谢迪迪埃。我知道 mongo 中的匹配,这就是我在控制台上查询文档的方式。问题是我何时需要使用 mgo 编写该行为。按照你所说的,我最好开始使用 bson.M 表示法。再次,非常感谢!
猜你喜欢
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 2018-07-28
  • 2019-05-09
  • 2018-03-17
  • 2014-09-14
相关资源
最近更新 更多