Cmdlets for MongoDB

Build 25.0.9434

Establishing a Connection

With the CData Cmdlets users can install a data module, set the connection properties, and start scripting. This section provides examples of using our MongoDB Cmdlets with native PowerShell cmdlets, like the CSV import and export cmdlets.

Connecting to MongoDB

Set the following connection properties to connect to a single MongoDB instance:

  • Server: Set this to the name or address of the server your MongoDB instance is running on. You can specify the port here or in Port.
  • Database: Set this to the database you want to read from and write to.

Connecting to MongoDB Using DNS Seed Lists

To connect using DNS seed lists
  • Server: Set this to "mongodb+srv://"" + the name of the server your MongoDB instance is running on. You can specify the port here or in Port.
  • Database: Set this to the database you want to read from and write to.
  • DNSServer: Set this to the hostname of a DNSServer that can resolve the necessary DNS entries.
Using DNS seed list connections allows for auto-detection of cluster topologies and more flexibility in deployment. See https://docs.mongodb.com/manual/reference/connection-string/#dns-seed-list-connection-format for more information.

Connecting to Replica Sets

To connect to a replica set, set the following in addition to the preceding connection properties:

  • ReplicaSet: Set this to a comma-separated list of secondary servers in the replica set, specified by address and port.
  • SlaveOK: Set this to true if you want to read from secondary (slave) servers.
  • ReadPreference: Set this to fine-tune how the cmdlet reads from secondary servers.

Securing MongoDB Connections

You can set UseSSL to negotiate SSL/TLS encryption when you connect.

Authenticating MongoDB Connections

Supported AuthScheme types (MONGODB-CR,SCRAM-SHA-1,SCRAM-SHA-256,PLAIN,GSSAPI) are challenge-response authentication and LDAP.

Challenge-Response

In challenge-response authentication, the User and Password properties correspond to a username and password stored in a MongoDB database. If you want to connect to data from one database and authenticate to another database, set both Database and AuthDatabase.

LDAP

To use LDAP authentication, set AuthDatabase to "$external" and set AuthScheme to PLAIN. This value specifies the SASL PLAIN mechanism; note that this mechanism transmits credentials over plaintext, so it is not suitable for use without TLS/SSL on untrusted networks.

X.509 Certificates

Set AuthScheme to X509 to use X.509 certificate authentication.

Connecting to an Amazon DocumentDB Cluster

Before you can connect to Amazon DocumentDB, you will first need to, ensure your Amazon DocumentDB cluster and the EC2 instance containing the mongo shell are currently running.

Next, configure an SSH tunnel to the EC2 instance as follows.

  1. From the AWS management console, select Services -> Database -> Amazon DocumentDB. From the DocumentDB management page, select Clusters, then click your cluster.
  2. Under the Connect section, note the --host value and its port found in the sample connection string.
  3. Navigate to Services -> Compute -> EC2. Select Running instances.
  4. Select your instance, then click the Connect button.
  5. Under the Example section, note the value identifying the instance and user, shown in the form <ami_username>@<Public DNS>
  6. In your preferred SSH client, establish a connection to your EC2 instance using the Host Name from the EC2 instance's Connect page (username@publicDNS) and Port 22.
  7. Provide your EC2 instance's private key file (in Putty, you will need to convert the keys from .pem to .ppk) for authentication.
  8. Configure an SSH tunnel using the port and host name from the DocumentDB cluster page.
  9. Establish the connection to the EC2 virtual machine.

Specify the following to connect to the DocumentDB cluster.

  • Server: Set this to the machine name which is hosting the SSH tunnel.
  • Port: Set this to the port the SSH tunnel is hosted on.
  • User: Set this to the master username used to provision the DocumentDB cluster.
  • Password: Set this to the master password set when provisioning the DocumentDB cluster.
  • UseSSL: Set this to true.
  • UseFindAPI Set this to true.

Connecting to CosmosDB with the MongoDB API

To obtain the connection string needed to connect to a Cosmos DB account using the MongoDB API, log in to the Azure Portal, select Azure Cosmos DB, and select your account. In the Settings section, click Connection String and set the following values.

  • Server: Set this to the Host value, the FQDN of the server provisioned for your account. You can also specify the port here or in Port.
  • Port: Set this to the port.
  • Database: Set this to the database you want to read from and write to.
  • User: Set this to the database user.
  • Password: Set this to the user's password.

Creating a Connection Object

You can then use the Connect-MongoDB cmdlet to create a connection object that can be passed to other cmdlets:

$conn = Connect-MongoDB -Server '127.0.0.1' -Port 27017 -Database 'test' -User 'test' -Password 'test'

Retrieving Data

The Select-MongoDB cmdlet provides a native PowerShell interface for retrieving data:

$results = Select-MongoDB -Connection $conn -Table "[CData].[Sample].Customers" -Columns @("City, CompanyName") -Where "Country='US'"
The Invoke-MongoDB cmdlet provides an SQL interface. This cmdlet can be used to execute an SQL query via the Query parameter.

Piping Cmdlet Output

The cmdlets return row objects to the pipeline one row at a time. The following line exports results to a CSV file:

Select-MongoDB -Connection $conn -Table [CData].[Sample].Customers -Where "Country = 'US'" | Select -Property * -ExcludeProperty Connection,Table,Columns | Export-Csv -Path c:\my[CData].[Sample].CustomersData.csv -NoTypeInformation

You will notice that we piped the results from Select-MongoDB into a Select-Object cmdlet and excluded some properties before piping them into an Export-CSV cmdlet. We do this because the CData Cmdlets append Connection, Table, and Columns information onto each row object in the result set, and we do not necessarily want that information in our CSV file.

However, this makes it easy to pipe the output of one cmdlet to another. The following is an example of converting a result set to JSON:

 
PS C:\> $conn  = Connect-MongoDB -Server '127.0.0.1' -Port 27017 -Database 'test' -User 'test' -Password 'test'
PS C:\> $row = Select-MongoDB -Connection $conn -Table "[CData].[Sample].Customers" -Columns (City, CompanyName) -Where "Country = 'US'" | select -first 1
PS C:\> $row | ConvertTo-Json
{
  "Connection":  {

  },
  "Table":  "[CData].[Sample].Customers",
  "Columns":  [

  ],
  "City":  "MyCity",
  "CompanyName":  "MyCompanyName"
} 

Deleting Data

The following line deletes any records that match the criteria:

Select-MongoDB -Connection $conn -Table [CData].[Sample].Customers -Where "Country = 'US'" | Remove-MongoDB

Modifying Data

The cmdlets make data transformation easy as well as data cleansing. The following example loads data from a CSV file into MongoDB, checking first whether a record already exists and needs to be updated instead of inserted.

Import-Csv -Path C:\My[CData].[Sample].CustomersUpdates.csv | %{
  $record = Select-MongoDB -Connection $conn -Table [CData].[Sample].Customers -Where ("_id = `'"+$_._id+"`'")
  if($record){
    Update-MongoDB -Connection $conn -Table [CData].[Sample].Customers -Columns @("City","CompanyName") -Values @($_.City, $_.CompanyName) -Where "_id  = `'$_._id`'"
  }else{
    Add-MongoDB -Connection $conn -Table [CData].[Sample].Customers -Columns @("City","CompanyName") -Values @($_.City, $_.CompanyName)
  }
}

Copyright (c) 2025 CData Software, Inc. - All rights reserved.
Build 25.0.9434