Export query as code
- MongoDB
Any query you build in Querybara can leave as a program: the find() of the collection tab, the
enabled stages of the aggregation editor, the translation of a SQL tab, or a query run in
IntelliShell. The program is complete, uses the official MongoDB driver for its language, and reads
the connection string from the MONGODB_URI environment variable, so it holds no credentials. A
mongosh script works the same way, for the MongoDB Shell.


Export a query
Section titled “Export a query”- Open the code:
- in the collection tab, choose the Query Code section, or press Ctrl + G (Cmd + G on macOS). It follows the query as you change it;
- in the aggregation editor or a SQL tab, choose Export code…;
- on a result tab of IntelliShell, choose Query code….
- Pick the Language. Querybara names the driver and the command that installs it; Copy beside it copies that command.
- Choose Copy code to copy the program, or Save as… to save it to a file.
Querybara remembers the language you picked last. In the collection tab, Open in IntelliShell beside the code opens the query in IntelliShell.
Languages
Section titled “Languages”| Language | Driver | Install | Suggested file name |
|---|---|---|---|
| Node.js | mongodb | npm install mongodb |
query.js |
| Python | PyMongo | pip install pymongo |
query.py |
| Java | MongoDB Java Driver (sync) | Maven: org.mongodb:mongodb-driver-sync |
Query.java |
| C# | MongoDB.Driver | dotnet add package MongoDB.Driver |
Program.cs |
| Go | mongo-go-driver v2 | go get go.mongodb.org/mongo-driver/v2/mongo |
main.go |
| PHP | mongodb/mongodb | composer require mongodb/mongodb |
query.php |
| Ruby | mongo (Ruby driver) | gem install mongo |
query.rb |
| mongosh | mongosh (the MongoDB Shell) | npm install -g mongosh |
query.mongosh.js |
The mongosh script switches to the query’s database, runs the find() with its sort, skip, limit
and other parts chained, or the aggregate(), and prints each document. Its values are written so
that mongosh reads them back with the same types.
Run the program
Section titled “Run the program”Set MONGODB_URI and run the file with the driver installed. For Python:
pip install pymongopython query.pyFor the mongosh script, pass the connection string on mongosh’s command line:
mongosh "$MONGODB_URI" --file query.mongosh.jsRelated
Section titled “Related”Documents Querybara 0.1.19 · built from89dc752