Golang mongodb 删除集合中的所有项 [mgo.v2]

huangapple go评论128阅读模式
英文:

Golang mongodb remove all items from collection [mgo.v2]

问题

如何使用GO语言从MongoDB中删除存储的集合中的所有项?

在Mongo控制台中,可以使用以下命令:

db.mycollection.remove({})

其中空括号{}表示所有文档模式。

在GO语言中(我使用"gopkg.in/mgo.v2"和"gopkg.in/mgo.v2/bson"),有以下方法:

sess.DB("mydb").C("mycollection").Remove(...)
或者
sess.DB("mydb").C("mycollection").RemoveAll(...)

但是,它们都需要实现选择器的参数。例如,选择器可以是一个bson映射:

bson.M{"id": id}

但我想删除所有元素,而不是特定的一个。

英文:

How to remove all items from collection stored in mongodb using GO lang?

In mongo console I can use:

db.mycollection.remove({})

where empty brackets {} mean all document pattern.

In GO lang (I use "gopkg.in/mgo.v2" and "gopkg.in/mgo.v2/bson") there are methods:

sess.DB("mydb").C("mycollection").Remove(...)
or
sess.DB("mydb").C("mycollection").RemoveAll(...)

but both of them needs parameter that implements selector. For example selector can be a bson map

bson.M{"id": id}

but I want to remove all elements, not a particular one.

答案1

得分: 5

请参考MongoDB文档:http://docs.mongodb.org/manual/tutorial/remove-documents/

要删除给定集合中的所有文档,只需使用空选择器调用RemoveAll方法。将nil作为参数传递应该可以正常工作:

sess.DB("mydb").C("mycollection").RemoveAll(nil)

但请确保检查返回的对象。

英文:

See the MongoDB documentation at:
http://docs.mongodb.org/manual/tutorial/remove-documents/

To remove all the documents of a given collection, just call RemoveAll with an empty selector. Just passing nil as a parameter should work fine:

sess.DB("mydb").C("mycollection").RemoveAll(nil)

Be sure to check the returned objects though.

答案2

得分: 1

根据@DidierSpezia的回答,使用C("mycollection").RemoveAll。然而,由于JSON规范区分了"空对象" {}和"null",你可能应该使用一个空的map[string]interface{}bson.M

sess.DB("mydb").C("mycollection").RemoveAll(bson.M{})
英文:

As per @DidierSpezia response use C("mycollection").RemoveAll. However since the JSON specification distinguishes between an "empty object" {} and "null", you should probably use an empty map[string]interface{} or bson.M.

sess.DB("mydb").C("mycollection").RemoveAll(bson.M{})

huangapple
  • 本文由 发表于 2015年1月2日 20:38:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/27742381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定