Docs Menu
Docs Home
/ /
MongoDB Command Line Interface
/

Customize the MongoDB CLI Output Using a Go Template

You can customize the MongoDB CLI output fields and format using a Go template. The template can be specified with the command for a simple output or through a separate file for a complex output. For information on the template, see Package template. For information on the types and properties available for each response, see:

You can specify a template with the command using the --output or -o option:

--output|-o go-template="{{<template>}}"

You can specify a template using a file using the --output or -o option:

--output|-o go-template-file="<path-to-template-file>"

The following command uses the template to retrieve a count of the number of projects in the specified organization using the default profile:

mongocli iam projects ls --orgId 5ab5cedf5g5h5i5j5kl12mn4 -o go-template="Count: {{.TotalCount}}"

The preceding command returns the following output:

Count: 2

The following mongocli atlas clusters describe command uses the template to retrieve the connection string for an Atlas cluster named getStarted. It uses the default profile for accessing Atlas.

mongocli atlas clusters describe getStarted -o go-template="Parse: {{.SrvAddress}}"

The previous command returns a string similar to the following:

Parse: mongodb+srv://getstarted.example.mongodb.net

You can use the MongoDB Shell, mongosh, to connect to the getStarted cluster with the srvAddress and the connection string. This example uses the following to connect to the Atlas cluster:

  • The connection string returned by the previous command

  • The username and password created in this tutorial

mongo "mongodb+srv://getstarted.example.mongodb.net" --username User1 --password ChangeThisPasswordToSomethingSecure

For example, consider the following file named template.tmpl:

Projects: {{range .Results}}{{.ID}} {{end}}

The following command uses the template.tmpl file to retrieve the IDs of the projects in the specified organization using the default profile:

mongocli iam projects ls --orgId 5ab5cedf5g5h5i5j5kl12mn4 -o go-template-file="template.tmpl"

The preceding command returns the following output:

Projects: 5e2211c17a3e5a48f5497de3 5f455b39749bea5fb575dccc

Back

Enable Autocomplete for the MongoDB CLI