@@ -819,6 +819,14 @@ defmodule Mongo.Ecto do
819819
820820 ## Mongo specific calls
821821
822+ @ migration Ecto.Migration.SchemaMigration . __schema__ ( :source )
823+
824+ special_regex = % BSON.Regex { pattern: "\\ .system|\\ $" , options: "" }
825+ migration_regex = % BSON.Regex { pattern: @ migration , options: "" }
826+ @ list_collections_query [
827+ "$and": [ [ name: [ "$not": special_regex ] ] , [ name: [ "$not": migration_regex ] ] ]
828+ ]
829+
822830 @ doc """
823831 Drops all the collections in current database.
824832
@@ -830,8 +838,25 @@ defmodule Mongo.Ecto do
830838 @ spec truncate ( Ecto.Repo . t ( ) , Keyword . t ( ) ) :: [ String . t ( ) ]
831839 def truncate ( repo , opts \\ [ ] ) do
832840 opts = Keyword . put ( opts , :log , false )
841+ version = db_version ( repo )
842+ [ major_version , minor_version | _ ] = version
843+
844+ collection_names =
845+ if major_version > 3 || ( major_version == 3 && minor_version >= 4 ) do
846+ all_collection_names =
847+ repo
848+ |> command ( % { listCollections: 1 } , opts )
849+ |> get_in ( [ "cursor" , "firstBatch" ] )
850+ |> Enum . filter ( & ( & 1 [ "type" ] == "collection" ) ) # exclude mongo views which were introduced in version 3.4
851+ |> Enum . map ( & Map . fetch! ( & 1 , "name" ) )
852+ |> Enum . reject ( & String . contains? ( & 1 , "system." ) )
853+
854+ all_collection_names -- [ @ migration ]
855+ else
856+ list_collections ( version , repo , opts )
857+ end
833858
834- Enum . map ( list_collections ( repo , opts ) , fn collection ->
859+ Enum . map ( collection_names , fn collection ->
835860 truncate_collection ( repo , collection , opts )
836861 collection
837862 end )
@@ -859,20 +884,12 @@ defmodule Mongo.Ecto do
859884 Connection . command ( repo , normalized , opts )
860885 end
861886
862- special_regex = % BSON.Regex { pattern: "\\ .system|\\ $" , options: "" }
863- @ migration Ecto.Migration.SchemaMigration . __schema__ ( :source )
864- migration_regex = % BSON.Regex { pattern: @ migration , options: "" }
865-
866- @ list_collections_query [
867- "$and": [ [ name: [ "$not": special_regex ] ] , [ name: [ "$not": migration_regex ] ] ]
868- ]
869-
870887 @ doc false
871888 def list_collections ( repo , opts \\ [ ] ) do
872889 list_collections ( db_version ( repo ) , repo , opts )
873890 end
874891
875- defp list_collections ( version , repo , opts ) when version >= 3 do
892+ defp list_collections ( [ major_version | _ ] , repo , opts ) when major_version >= 3 do
876893 colls = command ( repo , % { listCollections: 1 } , opts ) [ "cursor" ] [ "firstBatch" ]
877894
878895 all_collections =
@@ -904,8 +921,6 @@ defmodule Mongo.Ecto do
904921 end
905922
906923 defp db_version ( repo ) do
907- version = command ( repo , % { buildinfo: 1 } , [ ] ) [ "versionArray" ]
908-
909- Enum . fetch! ( version , 0 )
924+ command ( repo , % { buildinfo: 1 } , [ ] ) [ "versionArray" ]
910925 end
911926end
0 commit comments