MongoDB cheat sheet
96 one-line examples for MongoDB. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
Find Documents
| Code | What it does |
|---|---|
db.users.find() | Return all documents in the collection. |
db.users.findOne() | Return the first matching document. |
db.users.find({age: 30}) | Match documents where age equals 30. |
db.users.find({age: {$gt: 30}}) | Match documents where age is above 30. |
db.users.find({age: {$gte: 30}}) | Match documents where age is 30 or more. |
db.users.find({age: {$lt: 30}}) | Match documents where age is below 30. |
db.users.find({age: {$ne: 30}}) | Match documents where age is not 30. |
db.users.find({name: /^A/}) | Match names that start with the letter A. |
db.users.find({tags: "admin"}) | Match documents with admin in the tags array. |
db.users.find({}, {name: 1}) | Return only the name field and _id. |
db.users.find({}, {_id: 0, name: 1}) | Return only the name field. |
db.users.find().limit(5) | Return at most five documents. |
Insert and Update
| Code | What it does |
|---|---|
db.users.insertOne({name: "Ana"}) | Insert one new document. |
db.users.insertMany([{a: 1}, {a: 2}]) | Insert several documents in one call. |
db.users.updateOne({a: 1}, {$set: {b: 2}}) | Set field b on the first match. |
db.users.updateMany({a: 1}, {$set: {b: 2}}) | Set field b on all matches. |
db.users.updateOne({a: 1}, {$inc: {n: 1}}) | Add one to field n. |
db.users.updateOne({a: 1}, {$unset: {b: ""}}) | Remove field b from the document. |
db.users.updateOne({a: 1}, {$push: {tags: "x"}}) | Add x to the tags array. |
db.users.updateOne({a: 1}, {$pull: {tags: "x"}}) | Remove x from the tags array. |
db.users.replaceOne({a: 1}, {a: 9}) | Replace the whole document with a new one. |
db.users.updateOne({a: 1}, {$set: {b: 2}}, {upsert: true}) | Insert a new document when no match exists. |
db.users.deleteOne({a: 1}) | Delete the first matching document. |
db.users.deleteMany({a: 1}) | Delete all matching documents. |
Query Operators
| Code | What it does |
|---|---|
db.p.find({age: {$in: [20, 30]}}) | Match age equal to 20 or 30. |
db.p.find({age: {$nin: [20, 30]}}) | Match age not equal to 20 or 30. |
db.p.find({name: {$exists: true}}) | Match documents that have the name field. |
db.p.find({age: {$type: "int"}}) | Match documents where age is an integer. |
db.p.find({$and: [{a: 1}, {b: 2}]}) | Match documents that meet both conditions. |
db.p.find({$or: [{a: 1}, {b: 2}]}) | Match documents that meet either condition. |
db.p.find({a: {$not: {$gt: 5}}}) | Match documents where a is not above 5. |
db.p.find({tags: {$all: ["a", "b"]}}) | Match arrays that contain both values. |
db.p.find({tags: {$size: 2}}) | Match arrays with exactly two items. |
db.p.find({tags: {$elemMatch: {s: 1}}}) | Match array items that meet a condition. |
db.p.find({name: {$regex: "an", $options: "i"}}) | Match names that contain an, ignoring case. |
db.p.find({$where: "this.a > 1"}) | Match documents with a JavaScript expression. |
Sort, Limit, Project
| Code | What it does |
|---|---|
db.p.find().sort({age: 1}) | Sort results by age in ascending order. |
db.p.find().sort({age: -1}) | Sort results by age in descending order. |
db.p.find().sort({a: 1, b: -1}) | Sort by a ascending, then b descending. |
db.p.find().skip(10) | Skip the first ten documents. |
db.p.find().limit(10).skip(20) | Return ten documents after skipping twenty. |
db.p.find().count() | Count the documents in the result. |
db.p.countDocuments({a: 1}) | Count documents that match the filter. |
db.p.distinct("city") | Return the unique values of the city field. |
db.p.find({}, {name: 1, _id: 0}) | Return only the name field. |
db.p.find({}, {items: {$slice: 2}}) | Return only the first two array items. |
db.p.find().sort({_id: -1}).limit(1) | Return the newest document. |
db.p.find().explain() | Show the query plan for this find. |
Indexes
| Code | What it does |
|---|---|
db.p.createIndex({name: 1}) | Create an ascending index on name. |
db.p.createIndex({email: 1}, {unique: true}) | Create a unique index on email. |
db.p.createIndex({a: 1, b: -1}) | Create a compound index on two fields. |
db.p.createIndex({tags: 1}) | Create a multikey index on an array field. |
db.p.createIndex({name: "text"}) | Create a text index for text search. |
db.p.getIndexes() | List all indexes on the collection. |
db.p.dropIndex("name_1") | Remove the index with this name. |
db.p.dropIndexes() | Remove all indexes except _id. |
db.p.createIndex({a: 1}, {sparse: true}) | Index only documents that have field a. |
db.p.createIndex({a: 1}, {expireAfterSeconds: 3600}) | Delete documents one hour after field a. |
db.p.find({name: "Ana"}).explain("executionStats") | Check if the query uses the index. |
db.p.createIndex({a: 1}, {background: true}) | Build the index without blocking other operations. |
Aggregation
| Code | What it does |
|---|---|
db.p.aggregate([{$match: {a: 1}}]) | Filter documents at the start of the pipeline. |
db.p.aggregate([{$group: {_id: "$city"}}]) | Group documents by the city field. |
db.p.aggregate([{$group: {_id: null, n: {$sum: 1}}}]) | Count all documents in one group. |
db.p.aggregate([{$sort: {age: -1}}]) | Sort documents inside the pipeline. |
db.p.aggregate([{$limit: 5}]) | Keep only five documents. |
db.p.aggregate([{$skip: 5}]) | Drop the first five documents. |
db.p.aggregate([{$project: {name: 1}}]) | Keep only the name field. |
db.p.aggregate([{$unwind: "$tags"}]) | Create one document for each array item. |
db.p.aggregate([{$lookup: {from: "o", localField: "uid", foreignField: "_id", as: "o"}}]) | Join documents from another collection. |
db.p.aggregate([{$count: "total"}]) | Count documents and name the result total. |
db.p.aggregate([{$group: {_id: "$c", t: {$sum: "$n"}}}]) | Sum field n for each city group. |
db.p.aggregate([{$group: {_id: "$c", a: {$avg: "$n"}}}]) | Average field n for each city group. |
Database and Collection
| Code | What it does |
|---|---|
show dbs | List all databases on the server. |
use shop | Switch to the shop database. |
db | Show the current database name. |
show collections | List collections in the current database. |
db.createCollection("users") | Create an empty collection named users. |
db.users.drop() | Delete the users collection and its data. |
db.dropDatabase() | Delete the current database. |
db.stats() | Show storage statistics for the database. |
db.users.stats() | Show size and count for the collection. |
db.users.renameCollection("people") | Rename the collection to people. |
db.users.validate() | Check the collection for errors. |
db.users.dataSize() | Return the data size of the collection. |
Users, Backup, Help
| Code | What it does |
|---|---|
db.createUser({user: "ana", pwd: "pw", roles: []}) | Create a new database user. |
db.dropUser("ana") | Delete the user named ana. |
db.getUsers() | List users in the current database. |
db.grantRolesToUser("ana", ["read"]) | Give the read role to user ana. |
mongodump --db shop | Back up the shop database to disk. |
mongorestore dump/ | Restore data from a dump folder. |
mongoexport --db shop --collection users | Export the users collection as JSON. |
mongoimport --db shop --collection users --file u.json | Import JSON data into a collection. |
db.help() | Show help for database methods. |
db.users.help() | Show help for collection methods. |
db.serverStatus() | Show runtime status of the server. |
db.currentOp() | Show operations that run right now. |