Skip to content

Instantly share code, notes, and snippets.

@somahargitai
Last active April 16, 2023 20:12
Show Gist options
  • Save somahargitai/8cd9568b6a7ed6f263d251825c734026 to your computer and use it in GitHub Desktop.
Save somahargitai/8cd9568b6a7ed6f263d251825c734026 to your computer and use it in GitHub Desktop.
Mongo Cheatsheet

cheatsheet list

Mongo Database Cheatsheet

Content:

  1. Setup Mongo
  2. Tools
  3. Most used commands
  4. Mongoose
  • 4.1 Setting up a Model
  • 4.2 create new documents in database
  • 4.3 find queries
  • 4.4 update queries
  • 4.5 others
  1. export / import databas

1. Setup MongoDB

See more

Installation

Options:

Here I use the last option:

  docker pull mongo
  docker run -p 27018:27017 --name myAppDatabase mongo

2. Tools

  • Mongo Atlas
    Online free MongoDB. It provides also an online interface to browse documents
  • Mongo Compass
    GUI which can connect local and remote Mongo databases. Makes your life easier if you use locally installed or dockerized Mongo

3. Most used commands

4. Mongoose

note: I shortened the queries for a better focus, but of course you can always receive return values. You should also use then or await, because a mongo query always returns a thenable object (or a Promise if you use .exec() ).

  const allTheFruits = await Fruit.find();

Setting up a Model

create new documents in database

  • Create multiple documents
  Fruit.create(fruitArray);
  • Function to create one document:
async function newFruit({ name, color, ...optionalFields }) {
  Fruit.create({
    fruitName: name,
    color: color,
    ...optionalFields,
  });
}

await newFruit('orange', 'orange', ')

find queries

  • Find one item by id: Fruit.findById(bananaId)

  • Find all items in a collection: Fruit.find()

  • Example for find query with filtering:

    Customer.find({
      $and: [
        {
          $or: [
            {
              Country: "Germany",
            },
            {
              Country: "France",
            },
          ],
        },
        {
          VIP: true,
        },
      ],
    });
  • Filtering options:

    • $ne not equal (!=)
    • $eq equal (=)
    • $gt greater than (>)
    • $gte greater or equal than (>=)
    • $in in (in)
    • $lt less than (<)
    • $lte less or equal than (<=)
    • $nin not in (not in)

update queries

  • Add an item to a document's field which is an array

    const updatedMan  = await Man.updateOne(
        { _id: manId },
        { $push: { pastGirlfriends: SusansId } },
        done
    );

others

  Fruit.count();
  Fruit.deleteMany();

.lean()

export / import database

mongoexport --uri [mongo db connection url]/[database name] --collection [collection name] --out [filename].json
mongoimport --uri [mongo db connection url]/[database name] --collection  [collection name]  --drop --file [filename path].json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment