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

无法使用具有部分属性的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!

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

  {
 _id:{
 attr1:'foo',
 attr2:'bar'
},
 attr3  :'baz',
} 
  code>  pre> 
 
 

一个以上的文档在attr1条目中将具有相同的'foo'值。 我正在尝试删除所有这些。 为此,我得到了类似的内容: p>

  type DocId struct {
 Attr1字符串`bson:“ attr1,omitempty”`
 Attr2字符串`bson:“  attr2,omitempty“`
} 
 
type Doc struct {
 Id DocId`bson:” _ id,omitempty“`
 Attr3字符串`bson:” attr3,omitempty“`
} 
 
 
doc  := Doc {
 Id:DocId {Attr1:'foo'},
} 
 
collection:= session.DB(“ db”)。C(“ collection”)
collection.Remove(doc)
   code>  pre> 
 
 

这里的问题是我在remove调用中遇到了 Not found code>错误。 代码中有奇怪的地方吗? p>

非常感谢! p> div>

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.