Zoeken…
Opmerkingen
Het moeilijkste deel is om een subdocument aan het document toe te voegen dat nog niet is gemaakt. Als we het subdocument moeten hebben zoals verwacht, moeten we de array herhalen in een variabele en $doc2.add("Key", "Value")
plaats daarvan de foreach
huidige array met index gebruiken. Dit maakt het subdocument in twee regels, zoals u kunt zien in de "Tags" = [MongoDB.Bson.BsonDocument] $doc2
.
MongoDB met C # driver 1.7 met PowerShell
Ik moet alle details van de virtuele machine opvragen en bijwerken naar de MongoDB.
Which require the output look like this.
{
"_id" : ObjectId("5800509f23888a12bccf2347"),
"ResourceGrp" : "XYZZ-MachineGrp",
"ProcessTime" : ISODate("2016-10-14T03:27:16.586Z"),
"SubscriptionName" : "GSS",
"OS" : "Windows",
"HostName" : "VM1",
"IPAddress" : "192.168.22.11",
"Tags" : {
"costCenter" : "803344",
"BusinessUNIT" : "WinEng",
"MachineRole" : "App",
"OwnerEmail" : "[email protected]",
"appSupporter" : "Steve",
"environment" : "Prod",
"implementationOwner" : "[email protected]",
"appSoftware" : "WebServer",
"Code" : "Gx",
"WholeOwner" : "[email protected]"
},
"SubscriptionID" : "",
"Status" : "running fine",
"ResourceGroupName" : "XYZZ-MachineGrp",
"LocalTime" : "14-10-2016-11:27"
}
Ik heb 3 sets met array in Powershell
$MachinesList # Array
$ResourceList # Array
$MachineTags # Array
pseudo code
$mongoDriverPath = 'C:\Program Files (x86)\MongoDB\CSharpDriver 1.7';
Add-Type -Path "$($mongoDriverPath)\MongoDB.Bson.dll";
Add-Type -Path "$($mongoDriverPath)\MongoDB.Driver.dll";
$db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://127.0.0.1:2701/RGrpMachines');
[System.Collections.ArrayList]$TagList = $vm.tags
$A1 = $Taglist.key
$A2 = $Taglist.value
foreach ($Machine in $MachinesList)
{
foreach($Resource in $ResourceList)
{
$doc2 = $null
[MongoDB.Bson.BsonDocument] $doc2 = @{}; #Create a Document here
for($i = 0; $i -lt $TagList.count; $i++)
{
$A1Key = $A1[$i].ToString()
$A2Value = $A2[$i].toString()
$doc2.add("$A1Key", "$A2Value")
}
[MongoDB.Bson.BsonDocument] $doc = @{
"_id"= [MongoDB.Bson.ObjectId]::GenerateNewId();
"ProcessTime"= [MongoDB.Bson.BsonDateTime] $ProcessTime;
"LocalTime" = "$LocalTime";
"Tags" = [MongoDB.Bson.BsonDocument] $doc2;
"ResourceGrp" = "$RGName";
"HostName"= "$VMName";
"Status"= "$VMStatus";
"IPAddress"= "$IPAddress";
"ResourceGroupName"= "$RGName";
"SubscriptionName"= "$CurSubName";
"SubscriptionID"= "$subid";
"OS"= "$OSType";
}; #doc loop close
$collection.Insert($doc);
}
}
Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow