Mongodb
Mongodb
@ramchandrapadwal
1. Setup & Management
mongod: Start the MongoDB server.
mongo: Connect to a running MongoDB server.
mongos: Start a mongos server for sharding.
mongodump: Backup MongoDB database.
mongorestore: Restore MongoDB database from
backup.
mongoexport: Export a collection to JSON or CSV.
mongoimport: Import content from JSON or CSV
into a collection.
3. CRUD Operations
db.collection.insert(document): Insert a document.
db.collection.find(): Retrieve documents.
db.collection.update(criteria, changes): Update
documents.
@ramchandrapadwal
db.collection.delete(criteria): Delete documents.
db.collection.save(document): Update an existing
document or insert a new one.
db.collection.replaceOne(filter, replacement):
Replace a document.
4. Querying
db.collection.find({field: value}): Query by specific
field value.
db.collection.find({field: {$gt: value}}): Query for
documents where field value is greater than a
specified value.
db.collection.find().sort({field: 1}): Sort query results
in ascending order by field.
db.collection.find().limit(n): Limit query results to n
documents.
db.collection.find().skip(n): Skip the first n results of
a query.
db.collection.findOne(): Retrieve a single document.
db.collection.count(): Count documents that match
a query.
@ramchandrapadwal
5. Advanced Queries
db.collection.find({$or: [{field1: value1}, {field2:
value2}]}): Query using the OR condition.
db.collection.find({field: {$in: [value1, value2, ...]}}):
Query where field value is in the specified array.
db.collection.find({field: {$exists: true/false}}): Query
documents where a field does or doesn't exist.
db.collection.find({field: {$type: BSONType}}):
Query by BSON type.
6. Aggregation
db.collection.aggregate(): Process data and return
computed results.
$group: Group by some specified expression.
$sort: Sort documents.
$limit: Limit the number of documents.
$skip: Skip specified number of documents.
$unwind: Deconstructs an array field.
7. Indexing
db.collection.createIndex({field: 1}): Create an index
on a field.
db.collection.getIndexes(): List all indexes on a
collection.
db.collection.dropIndex(indexName): Remove an
index.
db.collection.reIndex(): Rebuild indexes.
@ramchandrapadwal
8. Administration
db.runCommand({commandName: 1}): Run a
database command.
db.dropDatabase(): Drop the current database.
db.collection.drop(): Drop a collection.
db.collection.stats(): Returns statistics about the
collection.
9. Replication
rs.initiate(): Initialize a new replica set.
rs.add(host): Add a member to the replica set.
rs.status(): View the status of the replica set.
rs.conf(): View the replica set's configuration.
rs.remove(host): Remove a member from the replica
set.
10. Sharding
sh.status(): Show sharding status.
sh.addShard(shardURL): Add a shard to a cluster.
sh.enableSharding(database): Enable sharding for a
database.
sh.shardCollection(namespace, key): Enable
sharding for a collection.
@ramchandrapadwal
11. Monitoring & Diagnostics
mongostat: Provide statistics about MongoDB's
state.
mongotop: Monitor read/write activity on a per-
collection level.
db.serverStatus(): Retrieve server status.
db.currentOp(): Show in-progress operations.
db.killOp(opid): Kill a specific operation.
@ramchandrapadwal
15. Storage
--storageEngine wiredTiger: Specify the WiredTiger
storage engine.
db.collection.storageSize(): Retrieve the storage size
for a collection.
db.collection.totalSize(): Retrieve the total size of a
collection including all indexes.
17. Utilities
db.fsyncLock(): Lock a mongod instance for
maintenance.
db.fsyncUnlock(): Unlock a mongod instance.
@ramchandrapadwal
19. GridFS
mongofiles: Utility for putting and getting files from
MongoDB GridFS.
db.fs.files.find(): Find files stored in GridFS.
@ramchandrapadwal
21. Advanced Features & Options
db.runCommand({collMod: "collection",
usePowerOf2Sizes: true}): Modify collection
options.
db.collection.isCapped(): Check if a collection is
capped.
--oplogSize: Set the oplog size.
--replSet "rsname": Start mongod as a member of
replica set "rsname".
db.setProfilingLevel(level): Set the database
profiling level.
db.getProfilingStatus(): Check the database
profiling status.
db.collection.aggregate([{ $lookup: options }]): Left
outer join of two collections.
--bind_ip: Bind MongoDB to listen to a specific IP
address.
--fork: Run MongoDB in the background.
--logpath: Specify the log file path.
@ramchandrapadwal
25. Schema Design
db.createCollection("name", options): Explicitly
creates a collection with options.
db.collection.isCapped(): Determines if a collection
is a capped collection.
$jsonSchema: Allows you to specify schema
validation in the collection level.
@ramchandrapadwal
28. Maintenance & Clean-up
db.repairDatabase(): Repairs the current database.
Use with caution as this can be blocking and
lengthy.
db.compactCollection(): Compacts a collection,
reducing storage use.
db.collection.reIndex(): Rebuilds all indexes on a
collection.
@ramchandrapadwal
31. TTL (Time-To-Live) Collections
db.collection.createIndex({field: 1},
{expireAfterSeconds: seconds}): Sets up a TTL index
which automatically removes documents after a
certain time.
32. Miscellaneous
db.setLogLevel(level): Changes the log level.
$redact: Reshapes each document in the stream by
restricting the content for each document based on
information stored in the documents themselves.
$merge: Writes the results of the aggregation
pipeline to a specified collection.
db.getReplicaSetStatus(): Returns the status of the
replica set from the POV of the server it's run on.
db.setFeatureCompatibilityVersion("version"): Sets
the feature compatibility version of MongoDB.
@ramchandrapadwal