← Back to MongoDB Course | Chapter 10: MongoDB with Node.js | Lesson 1 of 7

MongoDB का Node.js Driver

official mongodb package Node.js programs को MongoDB से connect करने और shell जैसे same operations चलाने देता है।

In this page:

  1. MongoDB Node.js Driver
Syntax
javascript
const { MongoClient } = require('mongodb');
const client = new MongoClient(connectionString);
await client.connect();
const collection = client.db('database').collection('collection_name');
const docs = await collection.find(filter).toArray();

MongoDB Node.js Driver

npm install mongodb से install करें, एक connection string से एक MongoClient बनाएँ, connect call करें, एक database और collection पाएँ, फिर insertOne, find(...).toArray(), और updateOne जैसे methods इस्तेमाल करें, सब promises return करते हुए।

काम खत्म होने पर client close करें, या app की पूरी lifetime के लिए एक client reuse करें।

Note: प्रति application एक MongoClient बनाएँ और इसे reuse करें।

उदाहरण: MongoDB Node.js driver

javascript
const { MongoClient } = require("mongodb");

async function main() {
  const client = new MongoClient(process.env.MONGODB_URI);
  await client.connect();
  const users = client.db("shop").collection("users");

  await users.insertOne({ name: "Ada", age: 36 });
  const adults = await users.find({ age: { $gte: 18 } }).toArray();
  console.log(adults.length);                 // 1
  await client.close();
}
main().catch(console.error);

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. प्रति request एक नया client बनाना
  2. driver calls पर await भूल जाना
  3. scripts में client close न करना
चैप्टर सारांश
  • npm install mongodb से install करें
  • MongoClient connect करता है
  • Collection methods promises return करते हैं
  • एक client reuse करें
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.