使用golang的mgo查询部分属性未找到文档

3

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

{
    _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)

这里的问题是我在调用删除函数时遇到了一个“未找到”的错误。 你能否在代码中看出任何奇怪的地方?
非常感谢!

代码中我看到一个奇怪的问题,就是因为 'foo' 导致它无法编译通过。 - user1804599
“Not found” 可能是由于集合名称拼写错误或没有符合条件的文档(例如,属性值拼写错误或已删除所有匹配项)导致的。您能确认这些不是问题吗? - icza
@rightfold,正如你所猜测的那样,这只是一个示例,你不需要执行它 ;) - ThisIsErico
@icza,我已经检查过了。我正在查询具有匹配条件的正确集合 :) - ThisIsErico
1个回答

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" }

您可以在文档中找到更多关于此主题的信息。

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

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

每次与 MongoDB 进行往返操作后,不要忘记测试错误。


非常感谢你,Didier。我知道在Mongo中如何匹配,这就是我在控制台上查询文档的方式。我的疑问是当我需要使用mgo编写该行为时。根据你的建议,我最好开始使用bson.M符号。再次感谢! - ThisIsErico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接