Last active
August 16, 2017 19:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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" | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice one!