PowerShell, MongoDB and Exporting GridFS Files

Posted on Posted in MongoDB, PowerShell

Still continuing along with the PowerShell, MongoDB and GridFS affair from my previous posts.

PowerShell, MongoDB and Searching GridFS
http://kowalski.ms/2012/07/25/powershell-mongodb-and-searching-gridfs/

PowerShell, MongoDB and GridFS File Uploads
http://kowalski.ms/2012/07/25/powershell-mongodb-and-gridfs-file-uploads/

We’re going to look at how you can quickly export files form MongoDB’s GridFS.

As mentioned in the previous articles, MongoDB comes with a mongofiles utility which will allow you to perform basic GET, PUT and LIST operations. Great for those quick sessions where you want to get a file or two, but what happens when it gets more involved? This is where this little script can come in handy.

The Script
As an example here, I’m searching for any files that have hit GridFS in the last 24 hours. Occasionally we’re interested in viewing the actual files and opening them up in their native applications from the file system.

Load your MongoDB C# Driver and Connect to MongoDB


#
# Load MongoDB C# Driver
#
Add-Type -Path "D:\Kristof\mongodb\MongoDB.Bson.dll"
Add-Type -Path "D:\Kristof\mongodb\MongoDB.Driver.dll"

#
# Connect to MongoDB
#
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://server01/mydatabase?safe=true')

Export Your Files


# Export files from gridfs
$fileDir = "D:\Kristof\gridfsexport"
$files = $db.GridFS.FindAll()
foreach ($file in $files) {
if ($file.UploadDate -ge (Get-Date).AddDays(-1)) {
$fileName = $file.Name.ToString()
Write-Host "Exporting" $file.Name ":: Uploaded " $file.UploadDate
$fd = "$fileDir$fileName"
$fs = New-Object System.IO.FileStream($fd,[System.IO.FileMode]'Create')
$file.GridFS.Download($fs, $filename)
$fs.Close()
}
else {
#"It's before the date"
}
}

So there you have it. A nice, simple, perfectly formed script which will allow you to export the contents based on a property, in this case UploadDate. Extend this to our hearts content and hope it helps someone else.

Enjoy,

Kristof

Leave a Reply

Your email address will not be published. Required fields are marked *