Guide to Applying query on you mongodb atlas hosted database from command line
Introduction¶
Often when you're using a database in a dev project, you want to access it quickly to check for modifications. When you're working with mysql database, you have a client that can help you with that. But what to do when you're using mongo db ? In this tutorial, i present how to access, from command line, your databased hosted with mongo db atlas. Then i showcase basic still important query examples. It should work also for those hosted locally.
Prerequistes¶
- Node js
- a mongo db database, offline or locally served
Download and Install Mongosh¶
You can download and install mongosh from the MongoDB website or using package managers like npm or yarn. Make sure you have Node.js installed on your system before proceeding.
Personally, using windows, i've downloaded it (and installed the setup) from the website, put the bin file (containing mongosh.exe) into environment variables and read a bit of the docu. However, using ubuntu, i've tested both approch, installing using apt-get and using nodejs.
Let's use the Package Manage option, as it is a more straightforward approach
This command will install mongosh it you doesn't have it.
For more details on installing mongosh, refer to the MongoDB documentation 1.
I figured later on i can install mongodb database tools in a Dockerfile like proposed here
Access a dababase from cli¶
I assume you have a MongoDB deployment to connect to. You can use a free cloud-hosted deployment like MongoDB Atlas or run a local MongoDB deployment.
Connect to your MongoDB deployment using mongosh by running the command 2
Replace <username>, <password>, <cluster-address>, and <database-name> with your own values.
You can find more information on how to install and use mongosh in the official MongoDB documentation 1 2.
Get one record by searching an attribute¶
Get all record on constraint¶
Get the list of _id for all articles
Get users whose prenoms contain abc, case insensitive
Find with cross tables constraints¶
Get all restaurants without an owner
Get all users whose _id is present in the restaurants table and are of type "RESTAU"
Get users with at least one restaurant and apply a modification
Update rows¶
Update the user with a specific _id
Update the user with a specific telephone
Update the password of all users with type="RESTAU
Other Commands¶
Conclusion¶
Note: This document contains example commands and use cases for the mongosh shell in MongoDB. Always be cautious when performing any updates or deletions on your database and ensure you have proper backups and permissions.