MongoDB NodeShell
Mingo's NodeShell let's you execute JavaScript code to work with data directly in Mingo.
This is NOT MONGO SHELL, though.
The command must be a regular async JS function with a return value.
This allows complex code with loops, conditions and variable initialization to be executed. This code must be a definition of an async function and should return something to see "results". You can use this to fetch and process data using JS code and return the result or update documents using a script with loop, etc.
Examples:
async function run() {
return await MyCollection.find({});
// this is the same as:
// return await db.collection("MyCollection").find({});
}
async function run() {
const docs = await Amenities.find({}).toArray();
for (const doc of docs) {
await Amenities.updateOne({_id: doc._id}, {$set: {something: "new"}})
}
return docs.length;
}
async function run() {
const oldSlug = await MingoPrompt('What was the old slug?')
const newSlug = await MingoPrompt('What will be the new slug?')
const confirmed = await MingoConfirm('You want to change ' + oldSlug + ' to ' + newSlug + '?');
if (!confirmed) return false;
const result = {
'Locations': await Locations.update({slug: oldSlug}, {
"$set": { "oldSlug": oldSlug, "slug": newSlug }
}),
'Attractions': await Attractions.updateMany({locationsCache: oldSlug}, {
"$set": { "locationsCache.$": newSlug }
}),
}
console.log('Locations and Attractions were updated.')
return result;
}
Variables available in the function's scope
You can use the following variables in your code:
- db: the current MongoDB database connection
- {CollectionName}: Every collection name is a variable pointing to that collection: db.collection("Amenities") === Amenities
- ObjectId: MongoDB wrapper for creating and manipulating ObjectIds
- dayjs: for work with dates
- _: lodash
- MingoConfirm(message): Simple confirm modal shown with specified message. Returns true if user clicked on OK and false on Cancel.
- MingoAlert(message): Simple alert modal shown with specified message.
- MingoPrompt(message): Simple prompt modal shown with specified message. Returns the value the user entered.
- console.log(), console.warn(), console.error() to show a customized console with messages you send.
History
NodeShell keeps track of all previous functions executed so you can return to any of them later. Once you have a long list of history, you may search for any function using a fulltext search.
Snippets and saved code
Mingo provides some example snippets. You may also save your code for later use. Code is saved for each database separately.