-3

I'm brand new to NoSQL and couldn't find anything in MongoDB's documentation about truncate?

I saw removing a collection but that seemed to worry me as it made me think I would be "deleting" the collection permanently.

Is there a way to truncate a collection with the same effect as it had in MySQL? I'm trying to do this in the .NET library and NOT in the MongoDB Shell...

Shadow
  • 33,525
  • 10
  • 51
  • 64
hello
  • 169
  • 10
  • 6
    Possible duplicate of [Truncate a collection](https://stackoverflow.com/questions/16493902/truncate-a-collection) – Raymond Nijland Feb 03 '18 at 00:06
  • How is that a duplicate? That's in a total different language? – hello Feb 03 '18 at 00:18
  • Did you read the linked dupe? There isn't an equivalent truncate operation in MongoDB so the language doesn't matter. – JohnnyHK Feb 03 '18 at 01:20
  • @JohnnyHK There isn't any drop function for .NET lol, I think you need to review your comment.. – hello Feb 03 '18 at 01:23
  • The point is that truncate would typically mean that you leave the collection in place with all defined indexes, but drop will completely delete the collection and its indexes. If you want to drop the collection instead, it would be good to update your question. – JohnnyHK Feb 03 '18 at 01:28
  • @JohnnyHK I just want to empty the table and delete its indexes, I have made it clear that I want to do exactly what the MySQL truncate does. – hello Feb 03 '18 at 01:29
  • :-) But that's not what MySQL truncate does. It would keep the indexes. Anyway, if you do want to completely delete your collection, see https://stackoverflow.com/questions/20696113/how-to-delete-a-mongodb-collection-using-collection-name-in-c-sharp – JohnnyHK Feb 03 '18 at 01:37
  • MySQL truncate would set the index back at 1, and remove everything in the table, that is what I'm trying to do. – hello Feb 03 '18 at 01:40
  • You're probably thinking of the auto-increment value being reset to 0 on truncate in MySQL, which doesn't apply to MongoDB because it doesn't support an auto-increment field. I'm referring to secondary indexes when I say dropping a collection will also delete its indexes. – JohnnyHK Feb 03 '18 at 01:42
  • So what do I do? I'm migrating my code from MySQL to MongoDB, sorry but this sort of confuses me, do I drop the collection or would that delete it? I just want to empty it then in that case, if auto-increment doesn't apply. – hello Feb 03 '18 at 01:43

1 Answers1

0

If you delete data from a collection, you can run the compact command on the collection affected. Suppose that you have a collection clients and you delete half of the contents, you can create a BsonDocument containing that command for that collection and execute it:

var result = db.RunCommand<BsonDocument>(new BsonDocument("compact", "clients"));

This does require a WiredTiger MongoDB engine though.

Hope this helps.