{"library":"node-red-node-mongodb","title":"Node-RED MongoDB Node","description":"This package provides Node-RED nodes for interacting with MongoDB databases, enabling users to store and retrieve data within their Node-RED flows. It abstracts the complexities of the MongoDB driver, allowing operations like `find`, `count`, `aggregate`, `save`, `insert`, `update`, and `remove` via message properties (`msg.payload`, `msg.query`, `msg.collection`). Originally part of Node-RED core, it was spun out as a separate installable package from Node-RED v0.10.8 onwards. The current stable version is 0.8.0, with a release cadence that seems to follow major Node-RED or MongoDB driver updates, marked by 'Milestone Release' entries. Key differentiators include its tight integration with the Node-RED flow paradigm and simplified database interactions for IoT and data processing scenarios. It requires a running MongoDB server and depends on a MongoDB client package version 3.6.3 or newer.","language":"javascript","status":"active","last_verified":"Thu Apr 23","install":{"commands":["npm install node-red-node-mongodb"],"cli":null},"imports":[],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"// This quickstart demonstrates direct MongoDB interaction\n// using the 'mongodb' driver, which is what the Node-RED node\n// 'node-red-node-mongodb' ultimately uses under the hood.\n// The Node-RED node provides a visual, flow-based interface\n// to these operations.\n//\n// To use the Node-RED node:\n// 1. Ensure Node.js and npm are installed.\n// 2. Install Node-RED globally: npm install -g node-red\n// 3. Start Node-RED: node-red\n// 4. Navigate to the Node-RED user directory (typically ~/.node-red).\n// 5. Install the MongoDB node: npm install node-red-node-mongodb\n// 6. Restart Node-RED and find the MongoDB nodes in the palette to build flows.\n\nimport { MongoClient } from 'mongodb';\n\nasync function runMongoExample() {\n  // For actual Node-RED use, connection string would be in node config.\n  const uri = process.env.MONGO_URI ?? 'mongodb://localhost:27017';\n  const dbName = 'nodeRedExampleDB';\n  const collectionName = 'sensorData';\n\n  const client = new MongoClient(uri);\n\n  try {\n    await client.connect();\n    console.log(\"Connected successfully to MongoDB server\");\n    const db = client.db(dbName);\n    const collection = db.collection(collectionName);\n\n    const dataToInsert = {\n      timestamp: new Date(),\n      temperature: Math.random() * 30 + 15, // Random temp between 15-45\n      humidity: Math.random() * 40 + 50,    // Random humidity between 50-90\n      location: 'serverRoom01',\n      _id: `sensor_${Date.now()}` // Example for handling _id\n    };\n\n    // Insert a document (equivalent to Node-RED 'out' node with 'Insert' operator)\n    const insertResult = await collection.insertOne(dataToInsert);\n    console.log(`Document inserted with _id: ${insertResult.insertedId}`);\n\n    // Find documents (equivalent to Node-RED 'in' node with 'Find' operator)\n    const query = { location: 'serverRoom01' };\n    const foundDocuments = await collection.find(query).limit(5).toArray();\n    console.log(`Found ${foundDocuments.length} documents:`);\n    foundDocuments.forEach(doc => console.log(doc));\n\n    // Update a document (equivalent to Node-RED 'out' node with 'Update' operator)\n    const updateResult = await collection.updateOne(\n        { _id: dataToInsert._id },\n        { $set: { temperature: 25.5, status: 'updated' } }\n    );\n    console.log(`Matched ${updateResult.matchedCount} docs, modified ${updateResult.modifiedCount} docs.`);\n\n  } catch (err) {\n    console.error(\"Failed to connect or perform MongoDB operations:\", err);\n  } finally {\n    await client.close();\n    console.log(\"MongoDB connection closed.\");\n  }\n}\n\nrunMongoExample();","lang":"javascript","description":"Demonstrates programmatic MongoDB interaction using the underlying driver, paralleling the operations provided by the Node-RED node, and provides installation steps for the Node-RED package itself.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}