MongoDB with the Node.js driver
Uses the official mongodb package 7.8. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”mongodb://app:secret@mongo.example.com:27017/shop?authSource=adminmongodb://app:secret@machnosql.example.com:27017/shop?authSource=adminThe address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'npm installnpm startSource
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
// Orders example for MongoDB, unchanged on MachNoSQL.import { MongoClient } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI);await client.connect();const orders = client.db().collection("orders");
await orders.deleteMany({});await orders.insertMany([ { customer: "ada", item: "keyboard", qty: 1, price: 49.0 }, { customer: "ada", item: "mouse", qty: 2, price: 19.5 }, { customer: "linus", item: "monitor", qty: 1, price: 199.0 },]);await orders.createIndex({ customer: 1 });
console.log(await orders.findOne({ item: "mouse" }, { projection: { _id: 0 } }));await orders.updateOne({ item: "mouse" }, { $inc: { qty: 1 } });
const revenue = await orders .aggregate([ { $group: { _id: "$customer", revenue: { $sum: { $multiply: ["$qty", "$price"] } } } }, { $sort: { revenue: -1 } }, ]) .toArray();console.log(revenue);
await client.close();{ "name": "machnosql-example-mongodb-node", "private": true, "type": "module", "scripts": { "start": "node app.js" }, "dependencies": { "mongodb": "^7.8.0" }}