NoSQLBooster for MongoDB is an electron-powered desktop application that embeds the latest mongosh engine (v2.8) and Node.js 22.x runtime. You can use any Node.js built-in global objects and modules (console, util,fs,path ...) and pure JS NPM packages in NoSQLBooster for MongoDB. It also adds mongoose-like fluent API, provides mb.runSQLQuery function, integrates a few utility modules (lodash, moment, shelljs, mathjs) to global scope to make the life inside of the MongoDB script a little bit easier.
Use Node.js Modules
Learn more about Using Node.js Modules in Your Script
import {existsSync} from "fs"; //ES6 module standard
existsSync("myFile");
const path=require("path");
path.resolve('/foo/bar', './baz');// Returns: '/foo/bar/baz'
const axios=require("axios"); //npm i axios //run it in NoSQLBooster for MongoDB user data directory
const rst = await axios.get('https://api.github.com/users/github'); // top-level await
console.log(rst.data);
Fluent Query API
NoSQLBooster for MongoDB supports mongoose-like fluent query builder API that enables you to build up a query using chaining syntax, rather than specifying a JSON object. All MongoDB query, projection and aggregate stage operators have a corresponding chainable method. Learn more about Fluent Query API, Operator Helper and cursor extension methods
// instead of writing:
db.user.find({age:{$gte:18,$lte:65}},{name:1,age:1,_id:0}).sort({age:-1, name:1});
// we can write:
db.user.where('age').gte(18).lte(65).select('name age -_id').sort("-age name");
// passing query conditions is permitted too
db.collection.find().where({ name: 'nosqlbooster' })
// chaining
db.collection
.where('age').gte(18).lte(65)
.where({ 'name': /^nosqlbooster/i })
.where('friends').slice(10)
NoSQLBooster exposes a new global variable, $, which converts chained MongoDB operator methods into a JSON object. We call it the operator helper.
$.gte(18).lte(65); // Operator Helper -> { $gte:18, $lte:65 }
$.gte(18).lte(65).build(); // got plain JSON object, Can be used in non mongosh method, { $gte:18, $lte:65 }
Chain aggregate stage operator and use cursor.getShellScript to get translated mongo shell script.
// aggregation
db.companies.aggregate()
.match($.where('founded_year').gte(2000).lte(2010)) //$: Operator helper
.group({_id:"$category_code",count:{$sum:1}})
.sort('-count')
.limit(100)
.getShellScript() //get translated mongo shell script
MongoDB commands supports EJSON as parameters
The Extended JSON format defines a reserved set of keys prefixed with "$" to represent field type information that directly corresponds to each type in BSON, the format that MongoDB uses to store data. The MongoDB shell usually uses JavaScript functions to represent MongoDB BSON types. The mongosh's CRUD methods can only use javascript BSON functions as parameters, and do not support EJSON formats, which requires conversion in order to use EJSON in queries. In V9, we have extended the mongosh shell methods to directly support EJSON as method parameters. Both canonical and relaxed formats are supported.
The following three queries are equivalent and can be used directly in V9.
EJSON Relaxed Mode
db.collection.find({
"_id": {
"$oid": "6368556b5dfec6090e3e4b6a"
},
"int32": 63480,
"int64": 4127753986432186,
"double": 33.99535545410777,
"date": {
"$date": "2021-11-19T03:16:06.652Z"
}
})
EJSON Extended (canonical format)
db.collection.find({
"_id": {
"$oid": "6368556b5dfec6090e3e4b6a"
},
"int32": {
"$numberInt": "63480"
},
"int64": {
"$numberLong": "4127753986432186"
},
"double": {
"$numberDouble": "33.99535545410777"
},
"date": {
"$date": {
"$numberLong": "1637291766652"
}
}
})
MongoDB Shell BSON Functions
db.collection.find({
oid: ObjectId("6368556b5dfec6090e3e4b6a"),
int32: 63480,
int64: NumberLong("4127753986432186"),
double: Double("33.99535545410777"),
date: ISODate("2021-11-19T11:16:06.652+08:00"),
})
We also added two editor commands for interchanging EJSON and mongo shell methods. Press Command+Shift+P to open command palette and enter "EJSON".
- Editor: Convert EJSON to mongosh Javascript Object
- Editor: Convert mongosh Javascript Object to EJSON
mb.runSQLQuery()
Global scope: mb.runSQLQuery(sql:string) method
With NoSQLBooster for MongoDB, you can run SQL SELECT Query against MongoDB. SQL support includes functions, expressions, aggregation for collections with nested objects and arrays. See the features and SQL examples supported by the NoSQLBooster for MongoDB.
Let's look at how to use the GROUP BY clause with the SUM function in SQL.
Instead of writing the MongoDB query which is represented as a JSON-like structure
db.employees.aggregate([
{
$group: {
_id: "$department",
total: { $sum: "$salary" }
},
}
])
You can query MongoDB by using familiar SQL which you probably already know
SELECT department, SUM(salary) AS total FROM employees GROUP BY department
Learn more about Query MongoDB with SQL
Top-level Await
Question
We have a situation where we want to call a function with an async callback.
Is there any way to use async operations in our MongoDB scripts?
Background:
We're intending to read a collection containing phone numbers, call Twilio API (an SMS service) to send a message, and finally store the status from Twilio into another collection.
Answer
NoSQLBooster 11.0 embeds the mongosh engine which supports native top-level await. You can use await directly at the top level of your scripts — it's the standard ES2022 await keyword, not a custom function.
Note: Shell-api methods like find(), insertOne(), aggregate() etc. do not need await — they are auto-resolved by the mongosh async-rewriter. Only your own custom Promises and non-shell-api async calls need await.
function sendSmsAsync(phone, message){ //promisify sendSms
return new Promise((resolve, reject)=> {
sendSms(phone, message, (status)=>{
resolve(status)
})
});
}
for (const user of db.users.find({}).toArray()) {
const status = await sendSmsAsync(user.phone, "A short message"); // top-level await
db.smsDeliveries.insertOne({status});
}
fetch()
NoSQLBooster 11.0 uses the Node.js built-in fetch API (available since Node.js 18+). No external packages needed.
Global scope: fetch
const textRes = await fetch('https://github.com/');
const text = await textRes.text();
console.log(text);
const jsonRes = await fetch('https://api.github.com/users/github');
const json = await jsonRes.json();
console.log(json);
NoSQLBooster for MongoDB integrates lodash, shelljs, momentjs and mathjs utility libraries. You can directly use lodash(_), shelljs, moment(moment) and mathjs in the global scope in your shell script.
lodash
A modern JavaScript utility library delivering modularity, performance, & extras. website: https://lodash.com/
Global scope: _
print(_.assign({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }));
// → { 'a': 1, 'b': 2, 'c': 3 }
print(_.map([1, 2, 3], n=> n * 3));
// → [3, 6, 9]
print("lodash.version",_.VERSION)
moment
Parse, validate, manipulate, and display dates and times in JavaScript. website: https://momentjs.com/
Tip: NoSQLBooster for MongoDB provides a new moment code snippets. Enter "moment" and press "Ctrl+Space" to start to autocomplete.
Global scope: moment
db.orders.find({ "ord_date" : {
$gte: moment("2017-07-06").startOf("day").toDate(),
$lte: moment("2017-07-07").endOf("day").toDate()
}
})
bluebird (Deprecated in v11)
Starting from NoSQLBooster 11.0, bluebird is no longer bundled. The native Promise implementation in Node.js 22.x is used instead. If you have scripts that rely on bluebird-specific APIs like Promise.promisifyAll, you can install it manually via npm:
npm i bluebird # run it in NoSQLBooster for MongoDB user data directory
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));
const content = await fs.readFileAsync("filename", "utf8");
shelljs
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. website: https://documentup.com/shelljs/shelljs
Global scope: shelljs
if (!shelljs.which('git')) {
shelljs.echo('Sorry, this script requires git');
shelljs.exit(1);
}
// Copy files to release dir
shelljs.rm('-rf', 'out/Release');
shelljs.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shelljs.cd('lib');
shelljs.ls('*.js').forEach(function (file) {
shelljs.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shelljs.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shelljs.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shelljs.cat('macro.js'), file);
});
mathjs
Math.js is an extensive math library for JavaScript and Node.js. website: http://mathjs.org/
Global scope: math
// functions and constants
print(math.round(math.e, 3)); // 2.718
print(math.atan2(3, -3) / math.pi); // 0.75
print(math.log(1000, 10)); // 3
print(math.sqrt(-4)); // 2i
print(math.pow([[-1, 2], [3, 1]], 2)); // [[7, 0], [0, 7]]
// expressions
print(math.eval('12 / (2.3 + 0.7)')); // 4
print(math.eval('5.08 cm to inch')); // 2 inch
print(math.eval('9 / 3 + 2i')); // 3 + 2i
print(math.eval('det([-1, 2; 3, 1])')); // -7
// chained operations
var a = math.chain(3)
.add(4)
.multiply(2)
.done();
print(a); // 14
print("math.version",math["version"])
