Tag Archives: Delete

Using the Mongo DB Shell to remove all elements in a collection

In my recent experiments with using MongoDB, I came across a need to remove all the records from a collection – the equivalent of DELETE FROM MYTABLE in SQL.

It turns out that, in order to do this, you need to use the Mongo DB Shell. This comes with Compass, although you may miss it, tucked away at the bottom:

By default it’s collapsed, but once you un-collapse it, you can do a number of things. The first thing you should do is tell it which DB you would like to use (for the purpose of this, let’s assume the database is called aardvark):

> use aardvark
< 'switched to db aardvark'

You can see which collections you have in the database, like this:

> db.getCollectionNames()
< [ 'collection1', 'collection2' ]

You can also see some information about a specific collection; for example:

> db.collection1.exists()

This should return a JSON document that details collection1.

In my case, I wanted to clear everything from the collection:

> db.collection1.deleteMany({ })

You can also pass this a specific filter, but this allows you to delete everything.




Deleting Files in a Storage Folder Using UWP

Just a little helper method that I used in a recent project to delete files, given a particular name, and excluding a provided list of files:

        internal static async Task DeleteTempFiles(ObservableCollection<StorageFile> exceptionFiles, StorageFolder folder, string fileNameStartsWith)
            var files = (await folder.GetFilesAsync())
                .Where(p => p.DisplayName.StartsWith(fileNameStartsWith)
                && !exceptionFiles.Any(e => e.DisplayName == p.DisplayName));            

            foreach(var file in files)
                await file.DeleteAsync(StorageDeleteOption.Default);                

You can call it like this:

	await FileHelper.DeleteTempFiles(Files, KnownFolders.PicturesLibrary, "_tmpFile");

It will delete all files in the Pictures folder starting with _tmpFile, and exclude anything in the Files collection.