MongoDB वापरकर्ता पुस्तिका

मूलभूत संकल्पना

डेटाबेस

डेटाबेस MongoDB मधील डेटासाठी शीर्ष-स्तरीय कंटेनर आहे. प्रत्येक डेटाबेसचे स्वतःचे संग्रह आणि परवानगी सेटिंग्ज असतात. तुम्ही MongoDB मध्ये अनेक डेटाबेस तयार करू शकता, प्रत्येक इतरांपासून स्वतंत्र.

संग्रह

संग्रह म्हणजे MongoDB डॉक्युमेंट्सचा एक गट, जो रिलेशनल डेटाबेसमधील टेबलसारखा असतो. संग्रहातील डॉक्युमेंट्समध्ये भिन्न फील्ड्स असू शकतात, ज्यामुळे संग्रह अत्यंत लवचिक होतात. रिलेशनल डेटाबेसच्या विपरीत, संग्रह कठोर, पूर्व-परिभाषित स्कीमा लागू करत नाहीत.

डॉक्युमेंट

डॉक्युमेंट हे MongoDB मधील मूलभूत डेटा एकक आहे, जे फील्ड आणि व्हॅल्यू जोड्यांनी बनलेले असते. डॉक्युमेंट्स JSON ऑब्जेक्ट्ससारखे असतात आणि BSON (Binary JSON) स्वरूप वापरून साठवले जातात.

BSON हे JSON डॉक्युमेंट्सचे बायनरी प्रतिनिधित्व आहे, ज्यात अतिरिक्त डेटा प्रकार समर्थन आहे. कमाल डॉक्युमेंट आकार 16 MB आहे.

MongoDB शी कनेक्ट करा

mongosh वापरून स्थानिक डेटाबेसशी कनेक्ट करा

mongosh

रिमोट डेटाबेसशी कनेक्ट करा

mongosh "mongodb://hostname:port"

प्रमाणीकरणासह कनेक्शन स्ट्रिंग वापरून कनेक्ट करा

mongosh "mongodb://username:password@hostname:port/database?authSource=admin"

URI वापरून कनेक्ट करा

mongosh "mongodb://localhost:27017,mongodb://localhost:27018/?replicaSet=myReplSet"

डेटाबेस ऑपरेशन्स

डेटाबेस पहा

show dbs

डेटाबेस स्विच/तयार करा

use mydatabase

टीप: use आदेशाने डेटाबेस स्विच करताना, डेटाबेस अस्तित्वात नसल्यास, MongoDB तो तयार करते, परंतु तुम्ही डॉक्युमेंट्स घालत नाही तोपर्यंत तो खरोखर तयार होत नाही.

वर्तमान डेटाबेस माहिती पहा

db.stats()

डेटाबेस ड्रॉप करा

db.dropDatabase()

संग्रह ऑपरेशन्स

संग्रह पहा

show collections

संग्रह तयार करा

db.createCollection("mycollection")

पर्यायांसह संग्रह तयार करा

db.createCollection("mycollection", {
  capped: true,
  size: 1000000,
  max: 100
})

संग्रह ड्रॉप करा

db.mycollection.drop()

संग्रह आकडेवारी पहा

db.mycollection.stats()

डॉक्युमेंट्स घाला

MongoDB संग्रहात डॉक्युमेंट्स घालण्यासाठी खालील मेथड्स प्रदान करते:

एकच डॉक्युमेंट घाला

db.users.insertOne({
  name: "John",
  age: 30,
  email: "[email protected]",
  address: {
    city: "New York",
    street: "Main Street"
  },
  hobbies: ["basketball", "swimming"]
})

अनेक डॉक्युमेंट्स घाला

db.users.insertMany([
  { name: "Jane", age: 25, city: "Los Angeles" },
  { name: "Bob", age: 35, city: "Chicago" },
  { name: "Alice", age: 28, city: "San Francisco" }
])

डॉक्युमेंट घाला (अप्रचलित परंतु उपलब्ध)

db.users.insert({
  name: "David",
  age: 32
})

घातलेला निकाल पहा

# View inserted document ID
db.users.insertOne({ name: "Test" })
# Returns: { acknowledged: true, insertedId: ObjectId("...") }

डॉक्युमेंट्स क्वेरी करा

सर्व डॉक्युमेंट्स क्वेरी करा

db.users.find()

हे SQL मधील SELECT * FROM users समतुल्य आहे.

एकच डॉक्युमेंट क्वेरी करा

db.users.findOne()

अटींसह क्वेरी करा

# Equality query
db.users.find({ age: 30 })

# Not equal query
db.users.find({ age: { $ne: 30 } })

# Greater than query
db.users.find({ age: { $gt: 25 } })

# Greater than or equal query
db.users.find({ age: { $gte: 25 } })

# Less than query
db.users.find({ age: { $lt: 30 } })

# Less than or equal query
db.users.find({ age: { $lte: 30 } })

# Range query
db.users.find({ age: { $gte: 20, $lte: 30 } })

लॉजिकल ऑपरेटर्स

# AND (default)
db.users.find({ age: { $gte: 25 }, name: "Jane" })

# OR
db.users.find({ $or: [{ age: { $gte: 30 } }, { name: "Bob" }] })

# NOR (neither nor)
db.users.find({ $nor: [{ age: { $lt: 20 } }, { city: "New York" }] })

# NOT
db.users.find({ age: { $not: { $gte: 25 } } })

अॅरे क्वेरी

# Array contains element
db.users.find({ hobbies: "basketball" })

# Array contains all elements
db.users.find({ hobbies: { $all: ["basketball", "swimming"] } })

# Array length
db.users.find({ hobbies: { $size: 2 } })

# Array element at specific position
db.users.find({ "hobbies.0": "basketball" })

# Array element matching condition
db.users.find({ hobbies: { $elemMatch: { $eq: "basketball" } } })

नेस्टेड डॉक्युमेंट क्वेरी

# Nested document field query
db.users.find({ "address.city": "New York" })

# Complete nested document match
db.users.find({ address: { city: "New York", street: "Main Street" } })

प्रोजेक्शन (केवळ निर्दिष्ट फील्ड्स परत करा)

# Return only name and email fields
db.users.find({ age: 30 }, { name: 1, email: 1 })

# Exclude a field
db.users.find({}, { age: 0 })

# Return all fields except _id
db.users.find({}, { _id: 0 })

क्रमवारी

# Sort by age ascending
db.users.find().sort({ age: 1 })

# Sort by age descending
db.users.find().sort({ age: -1 })

# Multi-field sort
db.users.find().sort({ age: -1, name: 1 })

मर्यादा आणि वगळणे

# Return first 5 documents
db.users.find().limit(5)

# Skip first 10 documents, return next 5 (pagination)
db.users.find().skip(10).limit(5)

# Count documents
db.users.countDocuments({ age: { $gte: 25 } })

# Estimate collection document count (fast but may be inaccurate)
db.users.estimatedDocumentCount()

कर्सर ऑपरेशन्स

# Use cursor
var cursor = db.users.find()
while (cursor.hasNext()) {
  printjson(cursor.next())
}

# forEach iteration
db.users.find().forEach(function(doc) {
  print("Name: " + doc.name)
})

डॉक्युमेंट्स अद्ययावत करा

एकच डॉक्युमेंट अद्ययावत करा

db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
)

अनेक डॉक्युमेंट्स अद्ययावत करा

db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

डॉक्युमेंट बदला

db.users.replaceOne(
  { name: "John" },
  { name: "John", age: 32, email: "[email protected]", city: "Boston" }
)

अद्ययावत ऑपरेटर्स

# $set - Set field value
db.users.updateOne({ name: "Jane" }, { $set: { age: 26 } })

# $unset - Remove field
db.users.updateOne({ name: "Jane" }, { $unset: { email: "" } })

# $inc - Increment/decrement
db.users.updateOne({ name: "Jane" }, { $inc: { age: 1 } })
db.users.updateOne({ name: "Jane" }, { $inc: { age: -1 } })

# $rename - Rename field
db.users.updateOne({ name: "Jane" }, { $rename: { "name": "fullname" } })

# $mul - Multiply
db.users.updateOne({ name: "Jane" }, { $mul: { age: 2 } })

# $min - Set minimum value
db.users.updateOne({ name: "Jane" }, { $min: { age: 20 } })

# $max - Set maximum value
db.users.updateOne({ name: "Jane" }, { $max: { age: 40 } })

# $push - Add element to array
db.users.updateOne({ name: "Jane" }, { $push: { hobbies: "running" } })

# $pull - Remove matching elements from array
db.users.updateOne({ name: "Jane" }, { $pull: { hobbies: "swimming" } })

# $addToSet - Add element to array (no duplicates)
db.users.updateOne({ name: "Jane" }, { $addToSet: { hobbies: "basketball" } })

# $pop - Remove first or last element from array
db.users.updateOne({ name: "Jane" }, { $pop: { hobbies: 1 } })

Upsert ऑपरेशन

# Insert if not exists, update if exists
db.users.updateOne(
  { name: "New User" },
  { $set: { age: 25, city: "Seattle" } },
  { upsert: true }
)

डॉक्युमेंट्स हटवा

एकच डॉक्युमेंट हटवा

db.users.deleteOne({ name: "John" })

अनेक डॉक्युमेंट्स हटवा

db.users.deleteMany({ age: { $lt: 20 } })

सर्व डॉक्युमेंट्स हटवा

db.users.deleteMany({})

अॅग्रिगेशन पाइपलाइन

अॅग्रिगेशन पाइपलाइन हे MongoDB च्या सर्वात शक्तिशाली वैशिष्ट्यांपैकी एक आहे, जे डेटा स्ट्रीम्सवर प्रक्रिया करण्यासाठी आणि जटिल डेटा रूपांतरण आणि विश्लेषण करण्यासाठी वापरले जाते.

मूलभूत वाक्यरचना

db.collection.aggregate([
  { $stage1: { ... } },
  { $stage2: { ... } },
  ...
])

सामान्य अॅग्रिगेशन स्टेजेस

$match - डॉक्युमेंट्स फिल्टर करा

db.users.aggregate([
  { $match: { age: { $gte: 25 } } }
])

$project - प्रोजेक्शन

db.users.aggregate([
  { $project: { _id: 0, name: 1, age: 1 } }
])

$group - गट

# Count users by age
db.users.aggregate([
  { $group: { _id: "$age", count: { $sum: 1 } } }
])

# Calculate average age
db.users.aggregate([
  { $group: { _id: null, avgAge: { $avg: "$age" } } }
])

# Group and collect names
db.users.aggregate([
  { $group: { _id: "$city", users: { $push: "$name" } } }
])

$sort - क्रमवारी

db.users.aggregate([
  { $sort: { age: -1, name: 1 } }
])

$limit - संख्या मर्यादित करा

db.users.aggregate([
  { $limit: 5 }
])

$skip - डॉक्युमेंट्स वगळा

db.users.aggregate([
  { $skip: 10 },
  { $limit: 5 }
])

$unwind - अॅरे विघटित करा

db.users.aggregate([
  { $unwind: "$hobbies" }
])

$lookup - संग्रह जोडा

# Assuming two collections: orders and products
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "productId",
      foreignField: "_id",
      as: "productDetails"
    }
  }
])

अॅग्रिगेशन ऑपरेटर्स

अंकगणित ऑपरेटर्स

db.sales.aggregate([
  {
    $project: {
      total: { $add: ["$price", "$tax"] },
      discount: { $multiply: ["$price", 0.1] }
    }
  }
])

स्ट्रिंग ऑपरेटर्स

db.users.aggregate([
  {
    $project: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      upperName: { $toUpper: "$name" }
    }
  }
])

दिनांक ऑपरेटर्स

db.users.aggregate([
  {
    $project: {
      year: { $year: "$birthdate" },
      month: { $month: "$birthdate" },
      day: { $dayOfMonth: "$birthdate" }
    }
  }
])

संपूर्ण उदाहरण

# Find the top three airlines with the most direct flights out of PDX
db.routes.aggregate([
  {
    $match: {
      "src_airport": "PDX",
      "stops": 0
    }
  },
  {
    $group: {
      _id: "$airline.name",
      count: { $sum: 1 }
    }
  },
  {
    $sort: { count: -1 }
  },
  {
    $limit: 3
  }
])

इंडेक्सेस

इंडेक्सेस MongoDB मधील क्वेरींची कार्यक्षम अंमलबजावणी समर्थन देतात. इंडेक्सेशिवाय, क्वेरी परिणाम परत करण्यासाठी MongoDB ला संग्रहातील प्रत्येक डॉक्युमेंट स्कॅन करावा लागतो.

इंडेक्सेस तयार करा

# Single field index
db.users.createIndex({ name: 1 })

# Descending index
db.users.createIndex({ age: -1 })

# Compound index
db.users.createIndex({ age: 1, name: 1 })

# Unique index
db.users.createIndex({ email: 1 }, { unique: true })

# Text index
db.users.createIndex({ description: "text" })

# Multikey index (array field)
db.users.createIndex({ hobbies: 1 })

# Geospatial index
db.locations.createIndex({ location: "2dsphere" })

# Hashed index
db.users.createIndex({ _id: "hashed" })

इंडेक्सेस पहा

# View all indexes on a collection
db.users.getIndexes()

# View index size
db.users.totalIndexSize()

इंडेक्सेस ड्रॉप करा

# Drop specified index
db.users.dropIndex("name_1")

# Drop all indexes (except _id index)
db.users.dropIndexes()

# Drop text index
db.users.dropIndex("description_text")

इंडेक्स गुणधर्म

# Sparse index (only indexes non-null values)
db.users.createIndex({ email: 1 }, { sparse: true })

# Partial index
db.users.createIndex(
  { email: 1 },
  { partialFilterExpression: { email: { $exists: true } } }
)

# TTL index (automatic expiration)
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }
)

इंडेक्सिंग धोरण शिफारसी

  • क्वेरी अटींमध्ये वारंवार वापरल्या जाणाऱ्या फील्ड्सवर इंडेक्सेस तयार करा
  • कंपाउंड इंडेक्सेसमधील फील्ड क्रम महत्त्वाचा आहे: अचूक जुळणी फील्ड्स प्रथम, श्रेणी क्वेरी फील्ड्स शेवटी ठेवा
  • उच्च लेखन वारंवारता असलेल्या संग्रहांवर खूप जास्त इंडेक्सेस तयार करणे टाळा
  • क्वेरी कार्यप्रदर्शनाचे विश्लेषण करण्यासाठी explain() वापरा

क्वेरी विश्लेषण

# Analyze query
db.users.find({ age: 25 }).explain()

# Analyze execution plan
db.users.find({ age: { $gte: 25 } }).sort({ name: 1 }).explain("executionStats")

रेप्लिका सेट ऑपरेशन्स

रेप्लिका सेट म्हणजे समान डेटासेट राखणाऱ्या MongoDB इन्स्टन्सचा एक गट, जो रिडंडन्सी आणि उच्च उपलब्धता प्रदान करतो.

रेप्लिका सेट आरंभित करा

rs.initiate()

रेप्लिका सेट स्थिती पहा

rs.status()

रेप्लिका सेट कॉन्फिगरेशन पहा

rs.conf()

सेकंडरी सदस्य जोडा

rs.add("hostname:27017")

आर्बिटर जोडा

rs.addArb("hostname:27017")

सदस्य काढा

rs.remove("hostname:27017")

रेप्लिका सेट निवडणुका

जेव्हा प्राथमिक अनुपलब्ध असतो, तेव्हा रेप्लिका सेट स्वयंचलितपणे निवडणूक घेतो. तुम्ही खालीलद्वारे निवडणूक ट्रिगर करू शकता:

# Force current node to become primary (use in specific situations)
rs.stepDown()

वाचन प्राधान्य

# Read from primary (default)
db.getMongo().setReadPref("primary")

# Read from secondary
db.getMongo().setReadPref("secondary")

# Read from nearest node
db.getMongo().setReadPref("nearest")

शार्डिंग ऑपरेशन्स

शार्डिंग हा MongoDB चा क्षैतिज स्केलिंगचा दृष्टिकोन आहे, जो डेटा अनेक सर्व्हरमध्ये वितरित करतो.

शार्डिंग सक्षम करा

sh.enableSharding("mydatabase")

संग्रह शार्ड करा

sh.shardCollection("mydatabase.mycollection", { _id: 1 })

शार्डिंग स्थिती पहा

sh.status()

शार्ड जोडा

sh.addShard("shard_replica_set/hostname:27017")

डेटा आयात आणि निर्यात

mongodump आणि mongorestore वापरणे

डेटा निर्यात करा

# Export entire database
mongodump --db=mydatabase --out=/backup

# Export specific collection
mongodump --db=mydatabase --collection=users --out=/backup

# Export with compression
mongodump --db=mydatabase --gzip --out=/backup

डेटा आयात करा

# Restore entire database
mongorestore --db=mydatabase /backup/mydatabase

# Restore specific collection
mongorestore --db=mydatabase --collection=users /backup/mydatabase/users.bson

# Restore with compression
mongorestore --db=mydatabase --gzip /backup/mongodb

mongoexport आणि mongoimport वापरणे

JSON म्हणून निर्यात करा

# Export as JSON
mongoexport --db=mydatabase --collection=users --out=users.json

# Export as JSON array
mongoexport --db=mydatabase --collection=users --out=users.json --jsonArray

# Export CSV
mongoexport --db=mydatabase --collection=users --out=users.csv --fields=name,age,email

JSON वरून आयात करा

# Import from JSON
mongoimport --db=mydatabase --collection=users --file=users.json

# Import from JSON array
mongoimport --db=mydatabase --collection=users --file=users.json --jsonArray

# Import from CSV
mongoimport --db=mydatabase --collection=users --file=users.csv --headerline

सामान्य प्रशासकीय आदेश

सर्व्हर स्थिती पहा

db.serverStatus()

वर्तमान डेटाबेस स्थिती पहा

db.stats()

संग्रह आकडेवारी पहा

db.users.stats()

वर्तमान ऑपरेशन्स पहा

db.currentOp()

मंद क्वेरी पहा

# View recent slow queries
db.system.profile.find().sort({ ts: -1 }).limit(10)

डेटाबेस सक्तीने बंद करा

# Use in emergencies only
db.adminCommand({ shutdown: 1 })

व्यवहार ऑपरेशन्स

MongoDB 4.0+ मल्टी-डॉक्युमेंट व्यवहारांना समर्थन देते.

मूलभूत व्यवहार

session = db.getMongo().startSession()
session.startTransaction({ readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } })

try {
  session.getDatabase("mydb").accounts.updateOne(
    { accountId: 1 },
    { $inc: { balance: -100 } }
  )
  session.getDatabase("mydb").accounts.updateOne(
    { accountId: 2 },
    { $inc: { balance: 100 } }
  )
  session.commitTransaction()
} catch (error) {
  session.abortTransaction()
  throw error
} finally {
  session.endSession()
}

परिवर्तन स्ट्रीम्स

परिवर्तन स्ट्रीम्स अनुप्रयोगांना रिअल-टाइममध्ये डेटा बदल ऐकण्यास परवानगी देतात.

# Listen for collection changes
var changeStream = db.users.watch()
while (changeStream.hasNext()) {
  printjson(changeStream.next())
}

GridFS

GridFS 16 MB मर्यादेपेक्षा जास्त मोठ्या फाइल्स साठवण्यासाठी वापरले जाते.

# Upload file
mongofiles put myfile.txt

# List files
mongofiles list

# Download file
mongofiles get myfile.txt

# Delete file
mongofiles delete myfile.txt