mongodbpowershellmongo-shell

Powershell, mongosh devops Pipeline. runs but never updates


Cant get the pipeline to work so brought it local This connects to Azure CosmosDB MongoDB with creds in connection string Opens new powershell window loads mongosh but crashes without error. No update to data in cosmosdb (mongodb instance)

# Set the path to your mongosh executable
$mongoShellPath = 'D:\MongoDB\Tools\mongosh.exe'

# Set your connection string
$connectionString = 'mongodb://TrustmeItWorks'

# Set the path to your JavaScript file
$mongoScriptPath = 'D:\MongoDB\Mikes.js'

# Construct the command
$evalArgument = "load(`"$mongoScriptPath`")"
$command = "& '$mongoShellPath' '$connectionString' --eval '$evalArgument'"

# Execute the command
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command $command" -Wait

Extra.. This will launch in the same powershell window and wait for the command Seems to need --eval in powershell to pass the "load("D:/MongoDB/Mikes.js")" method

"load("D:/MongoDB/Mikes.js")" the load method only works with the forward slashes not back in mongosh

# Set the path to your mongosh executable
$mongoShellPath = 'D:\MongoDB\Tools\mongosh.exe'

# Set your connection string
$connectionString = 'mongodb://TrustmeThisWorks'

# Construct the command
$command = "& '$mongoShellPath' '$connectionString'"

# Execute the command
Invoke-Expression $command

.js has this

var collection = 'MikesContext';

use('UpDogData');
db[collection].drop();
db.createCollection(collection);
db[collection].createIndex({ MikesId: 1 });

db[collection].insert({
    "_id": "98765309",
    "_t": "MikesContext",
    "MikesId": 65309,
    "MikesName": "Mike",
    "UWGuideLink": "https://mikedopp.com/happy.pdf",
    "KnowledgeBaseLink": ""
});

Stuck


Solution

  • "load("D:/MongoDB/Mikes.js")" does not work.

    But you can use one of these:

    However, you don't need neither --eval nor load(...). Simply use

    '$mongoShellPath' '$connectionString' 'D:\MongoDB\Mikes.js'
    

    db[collection] does not work either. Try db.getCollection(collection)

    Missing collections are created automatically, thus you can skip db.createCollection(collection)