Skip to content

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.

The Export code dialog for a find() on catalog.products, showing a ready-to-run PyMongo program with the filter, projection, sort and limit, and tabs for Node.js, Java, C#, Go and PHP.The Export code dialog for a find() on catalog.products, showing a ready-to-run PyMongo program with the filter, projection, sort and limit, and tabs for Node.js, Java, C#, Go and PHP.
Export any query as a working program in Python, Node.js and four more languages.
  1. Open the code:
  2. Pick the Language. Querybara names the driver and the command that installs it; Copy beside it copies that command.
  3. 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.

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.

Set MONGODB_URI and run the file with the driver installed. For Python:

Terminal window
pip install pymongo
export MONGODB_URI="mongodb+srv://[email protected]/"
python query.py

For the mongosh script, pass the connection string on mongosh’s command line:

Terminal window
mongosh "$MONGODB_URI" --file query.mongosh.js

Documents Querybara 0.1.19 · built from89dc752