Skip to content

Instantly share code, notes, and snippets.

@edoves
Forked from bradtraversy/mongodb_cheat_sheet.md
Last active October 30, 2024 15:22
Show Gist options
  • Save edoves/044cda0090d1097ff2f8ac3021c2d8d0 to your computer and use it in GitHub Desktop.
Save edoves/044cda0090d1097ff2f8ac3021c2d8d0 to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

MongoDB Cheat Sheet

Show All Databases

show dbs

Show Current Database

db

Create Or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections

show collections

Insert Row

db.posts.insert({
  title: 'Post One',
  body: 'Body of post one',
  category: 'News',
  tags: ['news', 'events'],
  user: {
    name: 'John Doe',
    status: 'author'
  },
  date: Date()
})

Insert Multiple Rows

db.posts.insertMany([
  {
    title: 'Post Two',
    body: 'Body of post two',
    category: 'Technology',
    date: Date()
  },
  {
    title: 'Post Three',
    body: 'Body of post three',
    category: 'News',
    date: Date()
  },
  {
    title: 'Post Four',
    body: 'Body of post three',
    category: 'Entertainment',
    date: Date()
  }
])

Get All Rows

db.posts.find()

Get All Rows Formatted

db.posts.find().pretty()

Find Rows

db.posts.find({ category: 'News' })

Sort Rows

# asc
db.posts.find().sort({ title: 1 }).pretty()
# desc
db.posts.find().sort({ title: -1 }).pretty()

Count Rows

db.posts.find().count()
db.posts.find({ category: 'news' }).count()

Limit Rows

db.posts.find().limit(2).pretty()

Chaining

db.posts.find().limit(2).sort({ title: 1 }).pretty()

Foreach

db.posts.find().forEach(function(doc) {
  print("Blog Post: " + doc.title)
})

Find One Row

db.posts.findOne({ category: 'News' })

Find Specific Fields

db.posts.find({ title: 'Post One' }, {
  title: 1,
  author: 1
})

Update Row

db.posts.update({ title: 'Post Two' },
{
  title: 'Post Two',
  body: 'New body for post 2',
  date: Date()
},
{
  upsert: true
})

Update Specific Field

db.posts.update({ title: 'Post Two' },
{
  $set: {
    body: 'Body for post 2',
    category: 'Technology'
  }
})

Increment Field ($inc)

db.posts.update({ title: 'Post Two' },
{
  $inc: {
    likes: 5
  }
})

Rename Field

db.posts.update({ title: 'Post Two' },
{
  $rename: {
    likes: 'views'
  }
})

Delete Row

db.posts.remove({ title: 'Post Four' })

Sub-Documents

db.posts.update({ title: 'Post One' },
{
  $set: {
    comments: [
      {
        body: 'Comment One',
        user: 'Mary Williams',
        date: Date()
      },
      {
        body: 'Comment Two',
        user: 'Harry White',
        date: Date()
      }
    ]
  }
})

Find By Element in Array ($elemMatch)

db.posts.find({
  comments: {
     $elemMatch: {
       user: 'Mary Williams'
       }
    }
  }
)

Add Index

db.posts.createIndex({ title: 'text' })

Text Search

db.posts.find({
  $text: {
    $search: "\"Post O\""
    }
})

Greater & Less Than

db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })

Here’s a quick cheat sheet for using Mongoose (Node.js library for MongoDB) to connect to MongoDB, define schemas, and perform CRUD operations.

1. Setup and Connection

  1. Install Mongoose:

    npm install mongoose
  2. Connect to MongoDB:

    const mongoose = require('mongoose');
    
    mongoose.connect('mongodb://localhost:27017/yourDatabase', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.error('Connection error', err));

Replace 'yourDatabase' with the name of your MongoDB database.


2. Creating a Schema and Model

Define a schema to structure documents within a MongoDB collection.

const { Schema } = mongoose;

const userSchema = new Schema({
    name: { type: String, required: true },
    age: { type: Number, min: 0 },
    email: { type: String, unique: true, required: true },
    createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

In this example, User is a model based on userSchema.


3. CRUD Operations

Create a Document

const newUser = new User({
    name: 'John Doe',
    age: 30,
    email: '[email protected]'
});

newUser.save()
    .then(user => console.log('User Created:', user))
    .catch(err => console.error(err));

Or, using create directly:

User.create({ name: 'Jane Doe', age: 25, email: '[email protected]' })
    .then(user => console.log('User Created:', user))
    .catch(err => console.error(err));

Read Documents

  1. Find all users:

    User.find()
        .then(users => console.log(users))
        .catch(err => console.error(err));
  2. Find with conditions:

    User.find({ age: { $gt: 20 } }) // users with age > 20
        .then(users => console.log(users))
        .catch(err => console.error(err));
  3. Find a single document:

    User.findOne({ email: '[email protected]' })
        .then(user => console.log(user))
        .catch(err => console.error(err));
  4. Find by ID:

    User.findById('userIdHere')
        .then(user => console.log(user))
        .catch(err => console.error(err));

Update Documents

  1. Update one document:

    User.updateOne({ email: '[email protected]' }, { age: 35 })
        .then(result => console.log('Update Result:', result))
        .catch(err => console.error(err));
  2. Update by ID:

    User.findByIdAndUpdate('userIdHere', { age: 40 }, { new: true })
        .then(user => console.log('Updated User:', user))
        .catch(err => console.error(err));
  3. Update multiple documents:

    User.updateMany({ age: { $lt: 30 } }, { age: 30 })
        .then(result => console.log('Update Result:', result))
        .catch(err => console.error(err));

Delete Documents

  1. Delete one document:

    User.deleteOne({ email: '[email protected]' })
        .then(result => console.log('Delete Result:', result))
        .catch(err => console.error(err));
  2. Delete by ID:

    User.findByIdAndDelete('userIdHere')
        .then(result => console.log('Deleted User:', result))
        .catch(err => console.error(err));
  3. Delete multiple documents:

    User.deleteMany({ age: { $gte: 40 } })
        .then(result => console.log('Delete Result:', result))
        .catch(err => console.error(err));

4. Mongoose Query Options

  • sort: Sorts results by a specified field.

    User.find().sort({ age: -1 }) // descending by age
  • limit: Limits the number of documents returned.

    User.find().limit(5) // returns only 5 documents
  • select: Limits the fields returned.

    User.find().select('name email') // only name and email fields

5. Using Middleware

Mongoose supports pre and post middleware for schema events.

userSchema.pre('save', function(next) {
    this.name = this.name.toLowerCase(); // convert name to lowercase before saving
    next();
});

6. Custom Static and Instance Methods

  1. Static Method (calls on model):

    userSchema.statics.findByName = function(name) {
        return this.find({ name: new RegExp(name, 'i') });
    };

    Usage:

    User.findByName('john')
        .then(users => console.log(users))
        .catch(err => console.error(err));
  2. Instance Method (calls on instance):

    userSchema.methods.isAdult = function() {
        return this.age >= 18;
    };

    Usage:

    const user = new User({ name: 'Alice', age: 20 });
    console.log(user.isAdult()); // true

This cheat sheet covers essential operations to get you started with Mongoose in Node.js. Let me know if you’d like more details on any specific part!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment