1

I'm trying to figure out, how to delete all elements from the collection or drop the collection? I'm using Laravel 4.2 and "jenssegers/mongodb":"~2.0".

Could you help me with this. Thank you!

Viktor
  • 819
  • 1
  • 12
  • 26

1 Answers1

10

Per its docs, "This library extends the original Laravel classes, so it uses exactly the same methods", so the same way you'd do it with any of the other database drivers.

Model::truncate() or Model::query()->delete() would remove all items. Dropping the collection is done with the Schema class's Schema::drop('model').

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • Any hints, on how to delete a single entry? Because `Model::query()->where()->delete()` does nothing. – Peon Aug 23 '16 at 11:47
  • 1
    @DainisAbols You'd need to get the single entry first - `Model::find(123)->delete()` or come up with a query that's specific enough like `Model::whereEmail('someone@example.com')->delete()`. – ceejayoz Aug 23 '16 at 14:15
  • 1
    Warning. Truncate will drop the indexes also... Well known bug, still here in the late 2019 – realtebo Oct 31 '19 at 11:38
  • @realtebo Woah. That's a hell of a caveat. – ceejayoz Oct 31 '19 at 12:34
  • 1
    @ceejayoz: I came here today because of this bug, and appreciated to fine the query()->delete() alternative; dropping index is NOT an alternative if you have scheduled jobs that needs to truncate collection AND you need your full_text composite weighted index – realtebo Oct 31 '19 at 14:02
  • unless you realize that Model::truncate() 7x time faster than Model::query()->delete() – Nikolay Shabak Jan 20 '20 at 15:10
  • @NikolayShabak Faster isn't the only consideration. The whole site might be slow if you forget to recreate the index, and a truncate resets the autoincrement ID. Important to understand all of the caveats. – ceejayoz Jan 20 '20 at 15:13
  • @ceejayoz does the mongo have an autoincrement ID? – Nikolay Shabak Feb 19 '20 at 15:37