HomeBlogLearn

Learn MongoDB

This page is under construction. In the meantime, Please check out the following MongoDB Tutorials:

Setup MongoDB in Cloud:

Install MongoDB Compass Mac:

Install MongoDB Compass Windows:

Inserting Documents: **See code below video**

records.txt

// inserts one document into "collection1" 
db.collection1.insertOne(
    {
        test: "Hello 123"
    }
);

// selects database "myapp" to run commands on.
use myapp;

// switch to different collection. just pretend it already exists.
db.pets.insertOne(
    {
        pet_name: "Chuck"
    }
)

// find all documents in "pets" collection
db.pets.find();


// insert multiple pets at a time:
db.pets.insertMany(
    [
        {
            pet_name: "Charlie",
        },
        {
            pet_name: "Pixie",
        }
    ]
)

// insert single document with multiple properties:
db.pets.insertOne(
    {
        pet_name: "josie",
        age: 4,
        isHungry: true
    }
);


// insert multiple documents each having multiple properties:
db.pets.insertMany(
    [
        {
            pet_name: "petA",
            age: 4,
            isHungry: false
        },
        {
            pet_name: "petB",
            age: 18,
            isHungry: true,
            weight: 136
        }
    ]
)


/// Insert MANY documents to play around with in future videos.
db.pets.insertMany(
    [
        {
            _id: "1",
            pet_name: "juice",
            breed: "maltese",
            age: 11,
            sex: "female",
            personality: "friendly",
            type: "dog"
        },
        {
            _id: "2",
            pet_name: "squack",
            breed: "parakeet",
            age: 4,
            sex: "male",
            personality: "loud",
            type: "bird"
        },
        {
            _id: "3",
            pet_name: "bobby",
            breed: "pigeon",
            age: 2,
            sex: "female",
            personality: "energetic",
            type: "bird"
        },
        {
            _id: "4",
            pet_name: "whalina",
            breed: "blue",
            age: 23,
            sex: "female",
            weight: 187000,
            type: "whale"
        },
        {
            _id: "5",
            pet_name: "Hershey",
            breed: "boxer",
            age: 3,
            sex: "male",
            personality: "playful",
            type: "dog"
        },
        {
            _id: "6",
            pet_name: "squeek",
            breed: "siamese",
            age: 15,
            sex: "male",
            weight: 2,
            type: "cat"
        },
        {
            _id: "7",
            pet_name: "kipper",
            breed: "greyhound",
            age: 5,
            sex: "male",
            neutered: true,
            type: "dog"
        },
        {
            _id: "8",
            pet_name: "noki",
            breed: "short-haired persian",
            age: 3,
            sex: "female",
            type: "cat"
        },
        {
            _id: "9",
            pet_name: "pooki",
            age: 3,
            sex: "female",
        },
        {
            _id: "10",
            pet_name: "snooki",
            age: 5,
            sex: "male",
        },
        {
            _id: "11",
            pet_name: "wooki",
            age: 4,
            sex: "male",
        }
    ]
)

Populate Collection with Sample Records

records.txt

db.pets.insertMany(
    [
        {
            _id: "1",
            pet_name: "juice",
            breed: "maltese",
            age: 11,
            sex: "female",
            personality: "friendly",
            type: "dog"
        },
        {
            _id: "2",
            pet_name: "squack",
            breed: "parakeet",
            age: 4,
            sex: "male",
            personality: "loud",
            type: "bird"
        },
        {
            _id: "3",
            pet_name: "bobby",
            breed: "pigeon",
            age: 2,
            sex: "female",
            personality: "energetic",
            type: "bird"
        },
        {
            _id: "4",
            pet_name: "whalina",
            breed: "blue",
            age: 23,
            sex: "female",
            weight: 187000,
            type: "whale"
        },
        {
            _id: "5",
            pet_name: "Hershey",
            breed: "boxer",
            age: 3,
            sex: "male",
            personality: "playful",
            type: "dog"
        },
        {
            _id: "6",
            pet_name: "squeek",
            breed: "siamese",
            age: 15,
            sex: "male",
            weight: 2,
            type: "cat"
        },
        {
            _id: "7",
            pet_name: "kipper",
            breed: "greyhound",
            age: 5,
            sex: "male",
            neutered: true,
            type: "dog"
        },
        {
            _id: "8",
            pet_name: "noki",
            breed: "short-haired persian",
            age: 3,
            sex: "female",
            type: "cat"
        },
        {
            _id: "9",
            pet_name: "pooki",
            age: 3,
            sex: "female",
        },
        {
            _id: "10",
            pet_name: "snooki",
            age: 5,
            sex: "male",
        },
        {
            _id: "11",
            pet_name: "wooki",
            age: 4,
            sex: "male",
        }
    ]
)

Basic Filtering:

basic-filtering.txt

// gets all the documents in the pets collection:
db.pets.find();

counts the # of documents in the query preceding the .count();
db.pets.find().count();


// returns all pets where the "sex" property has the value of "male"
db.pets.find(
    {
        sex: "male"
    }
);


// returns the number of documents that match the current filter:
db.pets.find(
    {
        sex: "male"
    }
).count();


// returns only records where sex is male AND type is dog
db.pets.find(
    {
        sex: "male",
        type: "dog"
    }
)

Filter with Less Than Exercise:

Documentation for less than

Filter with Less Than Solution:

filter-commands.txt

db.pets.find(
    {
        sex: "male",
        type: "dog"
    }
)

db.pets.find(
    {
        sex: "male"
    }
).count();



db.pets.find(
    {
        age: { $lte: 4}
    }
)

db.pets.find(
    {
        age: { $lte: 4}
    }
).count();

db.pets.find(
    {
        age: { $lt: 4}
    }
)

db.pets.find(
    {
        age: { $lt: 4}
    }
).count();

Get Documents with Or Conditional Exercise:

Get Documents with Or Conditional Solution:

or-conditional.txt

db.pets.find();

db.pets.find({
    $or: [
        {
            type: "dog"
        }
    ]
});

db.pets.find({
    $or: [
        {
            type: "dog"
        }
    ]
}).count(); //

db.pets.find({
    $or: [
        {
            type: "dog"
        },
        {
            type: "bird"
        }
    ]
});

db.pets.find({
    age: {$gte: 4},
    $or: [
        {
            type: "dog"
        },
        {
            type: "bird"
        },
    ]
});

Find Document by ObjectID:

find-by-objectid.txt

// used when the record you're looking for has the _id as a type of ObjectId.
db.pets.find({ _id: ObjectId('id_string here...') })

db.pets.findOne({ _id: ObjectId('id_string here...') })

// for our manually entered _ids where there is no "ObjectId" in the _id field.
db.pets.find({ _id: '1' });

db.pets.findOne({ _id: '1' });

Get if field exists Exercise:

Get if field exists Solution:

exists.txt

db.pets.find();


db.pets.find(
    {weight: { $exists: true} }
);

db.pets.find(
    {weight: { $exists: false} }
);

MongoDB Regex Exercise:

MongoDB Regex Solution:

regex.txt

// get all pets where the pet_name has an 'e' in the text.
db.pets.find(
    {
        pet_name: { $regex: 'e'}
    }
)

// count number of results
db.pets.find(
    {
        pet_name: { $regex: 'e'}
    }
).count()

// find all pets where pet_name has a capital 'E' right after a lowercase 'e'
// should not return any because there are no documents with 'eE' in the pet_name value.
db.pets.find(
    {
        pet_name: { $regex: 'eE'}
    }
)

// make it so capitalization differences don't affect the results.
// This is good to know because your users will be frustrated if a result doesn't show up due to capitalization errors.
// Imagine trying to find your friend "John" and can't because he put his name as "joHn".
db.pets.find(
    {
        pet_name: { $regex: 'eE', $options: 'i'}
    }
)

Deleting Documents in MongoDB:

delete.txt

db.pets.deleteOne(
    {type: "whale"}
)

db.pets.deleteMany(
    {
        breed: {$exists: false}
    }
)

Updating Documents in MongoDB

update.txt

db.pets.updateOne(
    {_id: "1"},
    {
        $set: {chunky: true}
    }
)


db.pets.find(
    {neutuered: {$exists: false}
})

// still only updates one
db.pets.update(
    {neutuered: {$exists: false}},
    {
        $set: {
            neutuered: false,
        }
    }
)

// updates many
db.pets.updateMany(
    {neutuered: {$exists: false}},
    {
        $set: {
            neutuered: false,
        }
    }
)

Unsetting Fields in MongoDB:

unset.txt

db.pets.insertOne(
    {
        pet_name: "coco",
        oops: "get rid of this",
        bad: "dont want this either",
        orthis: true,
    }
);

db.pets.deleteOne({pet_name: "coco"})

---- use above to add/remove the data we'll be playing with---

db.pets.updateOne(
    {pet_name: "coco"},
    {
        $unset: {oops: ""}
    }
)


db.pets.updateOne(
    {pet_name: "coco"},
    {
        $unset: {bad: "", orthis: ""}
    }
)

db.pets.updateOne(
    {pet_name: "coco"},
    [
        {
            $unset: ["oops", "orthis"]
        }
    ]
)

Aggregation Pipeline Intro:

Delete the existing pets collection (by clicking the delete button in mongodb cloud) and re-insert all the data with the below command:

insert-many-pets.txt

// reset pets:

db.pets.insertMany([

{
    _id: "1",
    pet_name: "juice",
    breed: "maltese",
    age: 11,
    sex: "female",
    personality: "friendly",
    type: "dog"
},
{
    _id: "2",
    pet_name: "squack",
    breed: "parakeet",
    age: 4,
    sex: "male",
    personality: "loud",
    type: "bird"
},
{
    _id: "3",
    pet_name: "bobby",
    breed: "pigeon",
    age: 2,
    sex: "female",
    personality: "energetic",
    type: "bird"
},
{
    _id: "4",
    pet_name: "whalina",
    breed: "blue",
    age: 23,
    sex: "female",
    weight: 187000,
    type: "whale"
},
{
    _id: "5",
    pet_name: "Hershey",
    breed: "boxer",
    age: 3,
    sex: "male",
    personality: "playful",
    type: "dog"
},
{
    _id: "6",
    pet_name: "squeek",
    breed: "siamese",
    age: 15,
    sex: "male",
    weight: 2,
    type: "cat"
},
{
    _id: "7",
    pet_name: "kipper",
    breed: "greyhound",
    age: 5,
    sex: "male",
    neutered: true,
    type: "dog"
},
{
    _id: "8",
    pet_name: "noki",
    breed: "short-haired persian",
    age: 3,
    sex: "female",
    type: "cat"
},
{
    _id: "9",
    pet_name: "pooki",
    age: 3,
    sex: "female",
},
{
    _id: "10",
    pet_name: "snooki",
    age: 5,
    sex: "male",
},
{
    _id: "11",
    pet_name: "wooki",
    age: 4,
    sex: "male",
}
])

The below "code block" is not meant to be run inside MongoDB Atlas. Below we're walking through the creation of our query one step at a time first.

aggregation.txt

//// find all documents where age is greater than or equal to 10.

// step 1: query for age, like normal.

age: { $gte: 10 }


// step 2: put into match:

$match: {
    age: { $gte: 10 }
}


// step 3.
// In aggregations there can be multiple stages, which all need to be in a separate object.
// this is an entire stage.
{
    $match: {
        age: { $gte: 10 }
    }
}

// step 4. aggregations are a list of stages.
[
    {
        $match: {
            age: { $gte: 10 }
        }
    }
]


step 5.
 // This is the final query from the steps above. We can run this.

db.pets.aggregate(
    [
        {
            $match: {
                age: { $gte: 10 }
            }
        }
    ]
)

aggregation2.txt

// stage 1. find all documents where the age is greater than or equal to 10.
// stage 2. take results from stage 1, and add the # of results and store the total sum of documents in "countyodude"

db.pets.aggregate(
    [
        {
            $match: {
                age: { $gte: 10 }
            }
        },
        {
            $group: {
                _id: null,
                countyodude: { $sum: 1},
            }
        }
    ]
)

aggregation3.txt

/// stage 1. Find all documents where age is greater than or equal to 10.
/// stage 2. take results from stage 1, store sum of results into countyodude, AND calculate the average age of results and store that value
// inside "avgdude"

db.pets.aggregate(
    [
        {
            $match: {
                age: { $gte: 10 }
            }
        },
        {
            $group: {
                _id: null,
                countyodude: { $sum: 1},
                avgdude: { $avg: "$age" }
            }
        }
    ]
)

Aggregate with a match + sum of documents

Aggregation 4

/// Get the total number of documents in pets, and average all the ages of all the documents.
db.pets.aggregate(
    [
        {
            $group: {
                _id: null,
                countyodude: { $sum: 1},
                avgdude: { $avg: "$age" }
            }
        }
    ]
)

/// Remove Unnecessary fields With $unset:

db.pets.aggregate(
    [
        {
            $match: {
                age: { $gte: 10 }
            }
        },
        {
            $unset: ["age", "sex"]
        }
    ]
)

One to Many Relationships in MongoDB:

Pets & Owners sample data:

sample-data.txt

db.pets.insertMany([

{
    _id: "1",
    pet_name: "juice",
    breed: "maltese",
    age: 11,
    sex: "female",
    personality: "friendly",
    type: "dog",
    owner_id: "1"
},
{
    _id: "2",
    pet_name: "squack",
    breed: "parakeet",
    age: 4,
    sex: "male",
    personality: "loud",
    type: "bird",
    owner_id: "2"
},
{
    _id: "3",
    pet_name: "bobby",
    breed: "pigeon",
    age: 2,
    sex: "female",
    personality: "energetic",
    type: "bird",
    owner_id: "2"
},
{
    _id: "4",
    pet_name: "whalina",
    breed: "blue",
    age: 23,
    sex: "female",
    weight: 187000,
    type: "whale",
    owner_id: "3"
},
{
    _id: "5",
    pet_name: "Hershey",
    breed: "boxer",
    age: 3,
    sex: "male",
    personality: "playful",
    type: "dog",
    owner_id: "1",
},
{
    _id: "6",
    pet_name: "squeek",
    breed: "siamese",
    age: 15,
    sex: "male",
    weight: 2,
    type: "cat",
    owner_id: "2",
},
{
    _id: "7",
    pet_name: "kipper",
    breed: "greyhound",
    age: 5,
    sex: "male",
    neutered: true,
    type: "dog",
    owner_id: "1"
},
{
    _id: "8",
    pet_name: "noki",
    breed: "short-haired persian",
    age: 3,
    sex: "female",
    type: "cat",
    owner_id: "3"
},
{
    _id: "9",
    pet_name: "pooki",
    age: 3,
    sex: "female",
    owner_id: "1"
},
{
    _id: "10",
    pet_name: "snooki",
    age: 5,
    sex: "male",
    owner_id: "2"
},
{
    _id: "11",
    pet_name: "wooki",
    age: 4,
    sex: "male",
    owner_id: "1"
}
])

///// Insert OWNERS //////////////

    db.owners.insertOne({_id: "1", name: "Joe", gender: "male", age: 15, occupation: "Lawn Mower"});
    db.owners.insertOne({_id: "2", name: "Joanna", gender: "female", age: 27, occupation: "Landscaper"});
    db.owners.insertOne({_id: "3", name: "Tom", gender: "male", age: 41, occupation: "Lawyer"});

Commands to setup one to many query:

one-to-many.txt

db.owners.aggregate(
        [
            {
                $lookup:
                {
                    from: "pets",
                    localField: "_id",
                    foreignField: "owner_id",
                    as: "owners_pets"
                }
            }
        ]
    )


/// remove fields not needed:

db.owners.aggregate(
        [
            {
                $lookup:
                {
                    from: "pets",
                    localField: "_id",
                    foreignField: "owner_id",
                    as: "owners_pets"
                }
            },
            {
                $unset: ["gender", "age", "owners_pets.sex", "owners_pets.breed", "owners_pets.age"]
            }
        ]
    )

Many to Many Relationships in MongoDB

Inserting sample data:

sample-data.txt

db.students.insertMany([
{
    _id: "1",
    name: "Joe",
    degree: "physics"
},
{
    _id: "2",
    name: "Cindy",
    degree: "Business"
},
{
    _id: "3",
    name: "Joey",
    degree: "Math"
},
{
    _id: "4",
    name: "Cynthia",
    degree: "Chemical Engineering"
},
{
    _id: "5",
    name: "Marilyn",
    degree: "Biology"
},
{
    _id: "6",
    name: "Mason",
    degree: "Basket Weaving"
},
{
    _id: "7",
    name: "Irina",
    degree: "physics"
},
{
    _id: "8",
    name: "Austin",
    degree: "Business"
}
])


db.classes.insertMany([
{
    _id: "1",
    teacher: "ms. Tilson",
    title: "Physics 101",
},
{
    _id: "2",
    teacher: "mr. Thedell",
    title: "Math 101",
},
{
    _id: "3",
    teacher: "ms. Fallen",
    title: "Math 260",
},
{
    _id: "4",
    teacher: "ms. Edwards",
    title: "Creative Writing",
},
{
    _id: "5",
    teacher: "mr. Sanders",
    title: "Accounting 101",
},
{
    _id: "6",
    teacher: "ms. Roosevelt",
    title: "Welding",
},
{
    _id: "7",
    teacher: "mr. Tyson",
    title: "Yoga",
}
]);

db.students_classes.insertMany([

{
    _id: "1",
    student_id: "1",
    class_id: "1",
},
{
    _id: "2",
    student_id: "1",
    class_id: "2",
},
{
    _id: "3",
    student_id: "1",
    class_id: "3",
},
{
    _id: "4",
    student_id: "1",
    class_id: "4",
},
{
    _id: "5",
    student_id: "1",
    class_id: "5",
},
{
    _id: "6",
    student_id: "1",
    class_id: "6",
},
{
    _id: "7",
    student_id: "1",
    class_id: "7",
},
{
    _id: "8",
    student_id: "2",
    class_id: "1",
},
{
    _id: "9",
    student_id: "2",
    class_id: "3",
},
{
    _id: "10",
    student_id: "2",
    class_id: "6",
},
{
    _id: "11",
    student_id: "2",
    class_id: "7",
},
{
    _id: "12",
    student_id: "3",
    class_id: "4",
},
{
    _id: "13",
    student_id: "3",
    class_id: "6",
},
{
    _id: "14",
    student_id: "4",
    class_id: "2",
},
{
    _id: "15",
    student_id: "4",
    class_id: "3",
},
{
    _id: "16",
    student_id: "4",
    class_id: "4",
},
{
    _id: "17",
    student_id: "5",
    class_id: "1",
},
{
    _id: "18",
    student_id: "5",
    class_id: "5",
},
{
    _id: "19",
    student_id: "5",
    class_id: "7",
},
{
    _id: "20",
    student_id: "6",
    class_id: "3",
},
{
    _id: "21",
    student_id: "6",
    class_id: "5",
},
{
    _id: "22",
    student_id: "7",
    class_id: "6",
},
{
    _id: "23",
    student_id: "7",
    class_id: "7",
},
{
    _id: "24",
    student_id: "7",
    class_id: "3",
}
])

many-to-many-aggregation.txt

// Connect students table to the students_classes table to see
// all the IDs of the classes the student is enrolled in
db.students.aggregate(
    [
        {
            $lookup:
            {
                from: "students_classes",
                localField: "_id",
                foreignField: "student_id",
                as: "class_ids"
            }
        }
    ]
)

// step 2. Take all the class_ids of the classes the student is taking, and join those onto the classes table, creating a many to many relationship between students and classes.

db.students.aggregate(
    [
        {
            $lookup:
            {
                from: "students_classes",
                localField: "_id",
                foreignField: "student_id",
                as: "class_ids"
            }
        },
        {
            $lookup:
            {
                from: "classes",
                localField: "class_ids.class_id",
                foreignField: "_id",
                as: "current_classes"
            }
        }
    ]
)

GeoSpatial Queries:

Sample Data:

sample-data.txt

db.games.insertMany(
[
{
    teamA: "Chickens",
    teamB: "Turkeys",
    sport: "Golf",
    time: "1230",
    whereat: {
        type: "Point",
        coordinates: [-122.349274, 47.620506], //longitude first, then latitude.
        address: "Space needle"
    }
},
{
    teamA: "Rhinos",
    teamB: "Goldfish",
    sport: "Chess",
    time: "1450",
    whereat: {
        type: "Point",
        coordinates: [-73.940033, 40.757801], //longitude first, then latitude.
        address: "Queens, New York"
    }
},
{
    teamA: "meerkats",
    teamB: "warthogs",
    sport: "hot dog eating",
    time: "0222",
    whereat: {
        type: "Point",
        coordinates: [-95.370800, 29.748690], //longitude first, then latitude.
        address: "2017 Main st Houston, Tx"
    }
},
{
    teamA: "red",
    teamB: "blue",
    sport: "Halo 2",
    time: "4:55pm",
    whereat: {
        type: "Point",
        coordinates: [-122.205986, 47.676891], //longitude first, then latitude.
        address: "Kirkland, WA"
    }
},
{
    teamA: "apes",
    teamB: "burrito boys",
    sport: "soccer",
    time: "4:20pm",
    whereat: {
        type: "Point",
        coordinates: [-122.441528, 47.253078], //longitude first, then latitude.
        address: "Tacoma, WA"
    }
},
])

Create the "index" on the "whereat" object with db.games.createIndex( {whereat: "2dsphere"} )

Find games within specified distance from the specified coordinates:

Geospatial-queries.txt

// get all games within 1000 meters of Everett. (returns 0 because 1000 meters isn't very far)
db.games.find({
    whereat: {
        $nearSphere: {
            $geometry: {
                type: "Point",
                coordinates: [-122.202080, 47.978985] // everett, wa
            },
            $maxDistance: 1000 // meters
        }
    }
})


// Returns 3 results: Everett & Tacoma are within 100000 meters of each other.
db.games.find({
    whereat: {
        $nearSphere: {
            $geometry: {
                type: "Point",
                coordinates: [-122.202080, 47.978985] // everett, wa
            },
            $maxDistance: 100000
        }
    }
})

// Finally gets all 5 results due to a much larger $maxDistance
db.games.find({
    whereat: {
        $nearSphere: {
            $geometry: {
                type: "Point",
                coordinates: [-122.202080, 47.978985] // everett, wa
            },
            $maxDistance: 10000000
        }
    }
})