6

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.

Abhay
  • 3,151
  • 1
  • 19
  • 29
user61253764
  • 478
  • 5
  • 9

2 Answers2

5

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.

Didier Spezia
  • 70,911
  • 12
  • 189
  • 154
1

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{})
wilsonfiifi
  • 291
  • 1
  • 2
  • 7