Home

MongoDB

Start/Stop Server

On Linux

sudo systemctl start mongod

sudo systemctl stop mongod

On Windows

Start terminal with admin rights

net start MongoDB

net stop MongoDB

MongoDb Shell Commands

// Connect to database
mongosh 

// Exit from shell
exit or quit or <CTRL> + D
    
// Show databases
show dbs

// Create new database and switch to it
use <name>

// Show collections (inside of a database)
show collections

// Create collection
db.createCollection("name")

// Drop collection
db.<name>.drop()

// Drop database
db.dropDatabase()

MongoDb Queries

myDb.user.find({ age: { $gte: 18 } });

myDb.user.findOne({ email: "john@example.com" });

myDb.user.findOne({ _id: ObjectId("5c8d123e7c32f10e00f60b01") });

myDb.user.updateOne({ _id: ObjectId("5c8d123e7c32f10e00f60b01") }, { $set: { age: 25 } });

myDb.user.updateMany({ isAdmin: true }, { $set: { isAdmin: false } });

myDb.user.deleteOne({ _id: ObjectId("5c8d123e7c32f10e00f60b01") });

myDb.user.deleteMany({ isAdmin: false });

Mongoose

Queries

Important note: The $setOperator works with mongoose and mongoDb queries and updates only the specified field but keeps other fields available in the document. Without it the other fields would be dropped.

const newUser = new User({ name: "John", age: 20, email: "john@example.com" });
newUser.save();

User.find({ age: { $gte: 18 } });
// Returns an array of all documents in the User collection where the age property is greater than or equal to 18. Without argument all entries are returned.

User.findOne({ email: "john@example.com" });
// Returns the first document in the User collection where the email property matches 'john@example.com'.

User.findById("5c8d123e7c32f10e00f60b01");
// Returns the document in the User collection with the specified _id property.

User.updateOne({ _id: "5c8d123e7c32f10e00f60b01" }, { age: 25 });
// Returns the number of matched documents and the number of modified documents.

User.updateMany({ isAdmin: true }, { isAdmin: false });
// Returns the number of matched documents and the number of modified documents.

User.deleteOne({ _id: "5c8d123e7c32f10e00f60b01" });
// Returns the number of matched documents and the number of deleted documents.

User.deleteMany({ isAdmin: false });
// Returns the number of matched documents and the number of deleted documents.

User.countDocuments({ age: { $gte: 18 } });
// Count the number of documents that match a query

Relationships

One-To-One

const userSchema = new Schema({
    name: String,
    email:String,
    password: String
})

const postSchema = new Schema({
    title: String,
    content: String,
    author: {type: Schema.Types.ObjectId, ref:"User"}
})

const User = model("User", userSchema);
const Post = model("Post", postSchema);

One-To-Many

const departmentSchema = newSchema({
    name: String,
    location: String,
    employee: [{type:Schema.Types.ObjectId, ref:"Employee"}]
})

const employeeSchema = newSchema({
    name:String,
    email:String,
    salary:Number,
    hireDate: Date
})

const Department = model("Department", departmentSchema);
const Employee = model("Employee", employeeSchema);

Many-To-Many

const courseSchema = new Schema({
    name: String,
    description: String,
    students: [{type:Schema.Types.ObjectId, ref:"Student"}]
})

const studentSchema = new Schema({
    name: String,
    email: String,
    course: [{{type:Schema.Types.ObjectId, ref:"Course"}}]
})

const Course = model("Course", courseSchema);
const Student = model("Student", studentSchema);

Automatically Delete Document (time based)

Create the TTL index on the updatedAt field

models/MyModel.js

mySchema.index(
  { updatedAt: 1 }, 
  { expireAfterSeconds: 60 * 60 * 24 * 365 } // 1 year
 );

// Model creation goes here

myModel.on('index', error => {
    if (error) {
      console.error('Error creating index:', error);
    } else {
      console.log('TTL index created');
    }
});