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
