Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Kieranties
Last active August 16, 2017 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Kieranties/5325695 to your computer and use it in GitHub Desktop.
Save Kieranties/5325695 to your computer and use it in GitHub Desktop.
A quick and dirty way of getting data from a csv into MongoDB. Knocked together for #NHTG13
<#
.NOTES
You'll need the excellent C# driver: http://docs.mongodb.org/ecosystem/drivers/csharp/
#>
Add-Type -Path "c:\mongodb\bin\MongoDB.Bson.dll"
Add-Type -Path "c:\mongodb\bin\MongoDB.Driver.dll"
Function Import-CsvToMongo{
param($path, $dbUrl, $collection, $matchCol) #matchCol is used as a lookup to check if entry is to be added or updated
$db = [MongoDB.Driver.MongoDatabase]::Create($dbUrl)
$collection = $db[$collection]
$sort = [MongoDB.Driver.Builders.SortBy]::Null
Import-Csv $path | % {
$q = [MongoDB.Driver.QueryDocument] @{ $matchCol = $_.$matchCol}
$update = New-Object MongoDB.Driver.Builders.UpdateBuilder
$i = $_
$i | Get-Member -MemberType NoteProperty | % {
$update.Set($_.Name, [MongoDB.Bson.BsonValue] $i.$($_.Name)) | out-null
}
$collection.FindAndModify($q, $sort, $update, $true, $true)
}
}
# Example call
<#
Import-CsvToMongo -path "C:\myfile.csv" `
-dbUrl "mongodb://localhost/trumptown?safe=true;slaveok=true" `
-collection "core" `
-matchCol "id"
#>
@dfinke
Copy link

dfinke commented Apr 6, 2013

Great! Thanks for posting

@tams89
Copy link

tams89 commented Jun 6, 2015

Nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment