UNPKG

@dataql/mongodb-adapter

Version:

MongoDB adapter for DataQL with zero API changes

291 lines (244 loc) 7.16 kB
import { MongoClient, ObjectId, connect, BSON } from "../src/index"; // Example 1: Using MongoClient directly async function mongoClientExample() { const client = new MongoClient("mongodb://localhost:27017/mydb", { dataql: { appToken: "demo-app-token", // Required for DataQL authentication env: "dev", }, }); await client.connect(); const db = client.db("testdb"); const collection = db.collection("users"); // Insert a document const insertResult = await collection.insertOne({ name: "John Doe", email: "john@example.com", age: 30, }); console.log("Inserted document with ID:", insertResult.insertedId); // Find documents const users = await collection.find({ age: { $gte: 18 } }).toArray(); console.log("Found users:", users); // Update a document const updateResult = await collection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } ); console.log("Modified count:", updateResult.modifiedCount); // Find one document const user = await collection.findOne({ name: "John Doe" }); console.log("Found user:", user); // Delete a document const deleteResult = await collection.deleteOne({ name: "John Doe" }); console.log("Deleted count:", deleteResult.deletedCount); await client.close(); } // Example 2: Using the connect helper async function connectExample() { const client = await connect("mongodb://localhost:27017/mydb", { dataql: { appToken: "demo-app-token", // Required for DataQL authentication env: "prod", }, }); const db = client.db("ecommerce"); const products = db.collection("products"); // Insert multiple documents const insertManyResult = await products.insertMany([ { name: "Laptop", price: 999.99, category: "electronics", inStock: true, }, { name: "Smartphone", price: 699.99, category: "electronics", inStock: true, }, { name: "Book", price: 19.99, category: "books", inStock: false, }, ]); console.log("Inserted products:", insertManyResult.insertedIds); // Query with cursor methods const cursor = products .find({ category: "electronics" }) .sort({ price: -1 }) .limit(2); console.log("Electronics products:"); await cursor.forEach((product) => { console.log(`- ${product.name}: $${product.price}`); }); // Count documents const count = await products.countDocuments({ inStock: true }); console.log("Products in stock:", count); // Distinct values const categories = await products.distinct("category"); console.log("Categories:", categories); await client.close(); } // Example 3: Working with ObjectIds async function objectIdExample() { const client = await connect("mongodb://localhost:27017/mydb"); const db = client.db("blog"); const posts = db.collection("posts"); // Create a custom ObjectId const customId = new ObjectId(); await posts.insertOne({ _id: customId, title: "My First Post", content: "This is a great blog post!", author: "Jane Doe", createdAt: new Date(), }); // Find by ObjectId const post = await posts.findOne({ _id: customId }); console.log("Found post:", post); // Using BSON utilities console.log("ObjectId is valid:", BSON.ObjectId.isValid(customId.toString())); console.log("ObjectId timestamp:", customId.getTimestamp()); await client.close(); } // Example 4: Bulk operations async function bulkOperationsExample() { const client = await connect("mongodb://localhost:27017/mydb"); const db = client.db("inventory"); const items = db.collection("items"); const bulkOps = [ { insertOne: { document: { name: "Widget A", quantity: 100, price: 10.5 }, }, }, { insertOne: { document: { name: "Widget B", quantity: 50, price: 15.75 }, }, }, { updateOne: { filter: { name: "Widget A" }, update: { $inc: { quantity: 10 } }, }, }, { deleteOne: { filter: { quantity: { $lt: 1 } }, }, }, ]; const result = await items.bulkWrite(bulkOps); console.log("Bulk operation result:", { insertedCount: result.insertedCount, modifiedCount: result.modifiedCount, deletedCount: result.deletedCount, }); await client.close(); } // Example 5: Advanced query patterns async function advancedQueryExample() { const client = await connect("mongodb://localhost:27017/mydb"); const db = client.db("social"); const users = db.collection("users"); // Insert test data await users.insertMany([ { username: "alice", email: "alice@example.com", profile: { age: 25, location: "New York", interests: ["photography", "travel", "music"], }, posts: [ { title: "My Trip to Paris", likes: 45 }, { title: "Photography Tips", likes: 23 }, ], }, { username: "bob", email: "bob@example.com", profile: { age: 30, location: "San Francisco", interests: ["coding", "gaming", "music"], }, posts: [ { title: "JavaScript Best Practices", likes: 67 }, { title: "Game Review: New RPG", likes: 12 }, ], }, ]); // Query with projection const usernames = await users .find({}, { projection: { username: 1, "profile.age": 1, _id: 0 } }) .toArray(); console.log("Usernames and ages:", usernames); // Complex query const musicLovers = await users .find({ "profile.interests": "music", "profile.age": { $gte: 25 }, }) .toArray(); console.log( "Music lovers 25+:", musicLovers.map((u) => u.username) ); // Update with array operations (simulated) await users.updateOne( { username: "alice" }, { $push: { "profile.interests": "cooking" } } ); // Find and modify const result = await users.findOneAndUpdate( { username: "bob" }, { $inc: { "posts.0.likes": 1 } }, { returnDocument: "after" } ); console.log("Updated Bob's first post likes:", result.value?.posts[0].likes); await client.close(); } // Run examples async function runExamples() { console.log("=== MongoDB Adapter Examples ===\n"); try { console.log("1. MongoClient Example:"); await mongoClientExample(); console.log("\n"); console.log("2. Connect Helper Example:"); await connectExample(); console.log("\n"); console.log("3. ObjectId Example:"); await objectIdExample(); console.log("\n"); console.log("4. Bulk Operations Example:"); await bulkOperationsExample(); console.log("\n"); console.log("5. Advanced Query Example:"); await advancedQueryExample(); console.log("\n"); console.log("All examples completed successfully!"); } catch (error) { console.error("Error running examples:", error); } } // Export for module usage export { mongoClientExample, connectExample, objectIdExample, bulkOperationsExample, advancedQueryExample, runExamples, }; // Run if this file is executed directly if (require.main === module) { runExamples(); }