Skip to content

Querying 🏹

Lyes S edited this page Jun 12, 2022 · 24 revisions

Table Of Contents

Create Documents

Create One Document

// Preparing a document
> doc = { "title": "Tacos", "desc" : "Yummie tacos", "cook_time" : 20 };

{ "title" : "Tacos", "desc" : "Yummie tacos", "cook_time" : 20 }

// Insert the document "doc" to "recipes" Collection
> db.recipes.insertOne(doc)

// Success.
{
        "acknowledged" : true,
        "insertedId" : ObjectId("62a29c6859e7529499943d7c")
}

Create Many Documents

> doc = { "title": "Tacos", "desc" : "Yummie tacos", "cook_time" : 20 };
{ "title" : "Tacos", "desc" : "Yummie tacos", "cook_time" : 20 }

> doc2 = { "title": "Tacos-2", "desc" : "Yummie tacos", "cook_time" : 20 };
{ "title" : "Tacos-2", "desc" : "Yummie tacos", "cook_time" : 20 }

// Insert an Array of Documents
> db.recipes.insertMany([doc, doc2]);
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("62a5304b5ea12a1ef17a0039"),
                ObjectId("62a5304b5ea12a1ef17a003a")
        ]
}

Read Documents

Find

Query Documents

// Find All Documents in "recipes" Collection
> db.recipes.find()

// Return Document(s) with an ID (it contains an encoded daytime) 
{ "_id" : ObjectId("62a29c6859e7529499943d7c"), "title" : "Tacos", "desc" : "Yummie tacos", "cook_time" : 20 }

// Find All Documents in "recipes" Collection and Display it with Pretty Print
> db.recipes.find().pretty()

// Return Document(s) and Display it Pretty 
{
        "_id" : ObjectId("62a29c6859e7529499943d7c"),
        "title" : "Tacos",
        "desc" : "Yummie tacos",
        "cook_time" : 20
}

Query a Specific Document

> db.recipes.find({"title" : "Tacos"}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "calories_per_serving" : 210,
        "cook_time" : 20,
        "desc" : "Classic Mexican tacos",
        "directions" : [
                "Brown beef",
                "Add taco seasoning and water, mix",
                "Bring to boil",
                "Lower heat to simmer 5-10 minutes until desired consistency",
                "Put meat in tacos"
        ],
        "ingredients" : [
                {
                        "name" : "ground beef (lean)",
                        "quantity" : {
                                "amount" : 1,
                                "unit" : "lbs"
                        }
                },
                {
                        "name" : "taco seasoning",
                        "quantity" : {
                                "amount" : 2,
                                "unit" : "oz"
                        }
                },
                {
                        "name" : "corn hard tacos",
                        "quantity" : {
                                "amount" : 12,
                                "unit" : "oz"
                        }
                }
        ],
        "likes" : [
                1,
                415
        ],
        "likes_count" : 2,
        "prep_time" : 10,
        "rating" : [
                4,
                4,
                3,
                4,
                2,
                5,
                2,
                2,
                4,
                5
        ],
        "rating_avg" : 3.5,
        "servings" : 4,
        "tags" : [
                "mexican",
                "quick",
                "easy",
                "ground beef"
        ],
        "type" : "Dinner"
}

Query a Specific Document with a Specific Attributes

By default, the query result returns all document fields. It is possible to specify the fields you want. To do so, you need to provide a second parameter to find (include attribute = 1).

// Find a document with title "Tacos". The result document should return only "title" attribute. 
> db.recipes.find({"title" : "Tacos"}, {"title" : 1}).pretty();

{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
// Find a document with title "Tacos". The result document should return "title" and "type" attributes. 
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "type" : 1}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "type" : "Dinner"
}

Query a Specific Document with a Specific Attributes to Include and Exclude

By default, the query result returns all document fields. It is possible to specify the fields you want. To do so, you need to provide a second parameter to find (include attribute = 1, exclude attribute = 0).

// Find a document with title "Tacos". The result document should return "title" and "type" attributes and exclude the Id. 
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "type" : 1, "_id" : 0}).pretty();

{ "title" : "Tacos", "type" : "Dinner" }

Query a Specific Document with a Regex

// Find a document with title based on a regex. The result documents should return "title" attribute. 
> db.recipes.find({"title" : {$regex : /taco/i }}, {"title" : 1});
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }

Limit

The limit() function in MongoDB is used to specify the maximum number of results to be returned.

> db.recipes.find({ "title" : {$regex : /taco/i} }, {"title" : 1}).limit(1).pretty();
{
        "_id" : ObjectId("5e6fd805fa98021236426a24"),
        "title" : "Chicken Soft Tacos"
}

Sort

The sort() method consists of two basic building blocks. These building blocks are fields to be sorted and the sort order. [1]

  • 1 : ASC
> db.recipes.find({}, {"title" : 1}).sort({"title" : 1})

{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
  • -1 : DESC
> db.recipes.find({}, {"title" : 1}).sort({"title" : -1})

{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }

Skip

The skip() method will skip the first n document from the query result

> db.recipes.find({}, {"title" : 1}).sort({"title" : -1}).skip(2);

{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }

Comparison Query Operators

  • $lt : Matches values that are less than a specified value.
  • $lte : Matches values that are less than or equal to a specified value.
  • $gt : Matches values that are greater than a specified value.
  • $gte : Matches values that are greater than or equal to a specified value.
  • $in : Matches any of the values specified in an array.

Logical Query Operators

AND

// Find documents titles in recipes where cook_time <= 30 min **and** preparation time <= 10 min
> db.recipes.find({ "cook_time" : {$lte : 30}, "prep_time" : {$lte : 10} }, {"title" : 1});

{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }

OR

// Find documents titles in recipes where cook_time <= 30 min **or** preparation time <= 10 min
> db.recipes.find({ $or : [{"cook_time":{$lte:30}} , {"prep_time":{$lte:10}}] }, {"title" : 1});

{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }

Array Query Operators

All

Matches arrays that contain all elements specified in the query.

> db.recipes.find( {"tags" : { $all : ["easy", "quick"] } }, {"title" : 1, "tags" : 1}).pretty()

{
        "_id" : ObjectId("5e6fd805fa98021236426a24"),
        "title" : "Chicken Soft Tacos",
        "tags" : [
                "mexican",
                "quick",
                "easy",
                "chicken"
        ]
}
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "tags" : [
                "mexican",
                "quick",
                "easy",
                "ground beef"
        ]
}

In

Matches any of the values specified in an array.

> db.recipes.find({"tags" : { $in : ["easy", "quick"] } }, {"title" : 1, "tags" : 1} ).pretty()

{
        "_id" : ObjectId("5e6fd805fa98021236426a24"),
        "title" : "Chicken Soft Tacos",
        "tags" : [
                "mexican",
                "quick",
                "easy",
                "chicken"
        ]
}
{
        "_id" : ObjectId("5e87856d07beb474c074c5ca"),
        "title" : "Brown Sugar Meatloaf",
        "tags" : [
                "ground beef",
                "family meal",
                "easy"
        ]
}
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "tags" : [
                "mexican",
                "quick",
                "easy",
                "ground beef"
        ]
}
{
        "_id" : ObjectId("5edf1d313260aab97ea0d589"),
        "title" : "Zucchini Brownies",
        "tags" : [
                "sweets",
                "easy"
        ]
}

Update Documents

Update Fields

Set

The Set operator replaces the value of a field with the specified value

Note :

  • If the attribute does not exist, it will be inserted.
> db.recipes.find({}, {"title" : 1});
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a0039"), "title" : "Tacos" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a003a"), "title" : "Tacos-2" }

// Update Title : "Maple Smoked Salmon" to "Maple Smoked Salmon v2" 
> db.recipes.updateOne({"title" : "Maple Smoked Salmon"}, {$set : { "title" : "Maple Smoked Salmon v2"}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

// Update vegan attribute. It will be added as it is not available
> db.recipes.updateOne({"title" : "Maple Smoked Salmon v2"}, {$set : { "vegan" : false}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Unset

The unset operator deletes a particular field.

// Given the following document where we inserted a new field
> db.recipes.find({"title" : "Maple Smoked Salmon v2"}, { "title" :1, "vegan" : 1 }).pretty()
{
        "_id" : ObjectId("5e878f5220a4f574c0aa56db"),
        "title" : "Maple Smoked Salmon v2",
        "vegan" : false
}

// In order to delete "vegan" field, we will perform an unset
> db.recipes.updateOne({"title" : "Maple Smoked Salmon v2"}, {$unset:{"vegan":1}});

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Inc

The inc operator increments a field by a specified value.

// Given the field "likes_count", we would like to increment the existing value by 1 
> db.recipes.find({"title" : "Maple Smoked Salmon v2"}, {"title" : 1, "likes_count" : 1}).pretty()
{
        "_id" : ObjectId("5e878f5220a4f574c0aa56db"),
        "title" : "Maple Smoked Salmon v2",
        "likes_count" : 1
}

// Inc operator usage on update
> db.recipes.updateOne({"title" : "Maple Smoked Salmon v2"}, {$inc : {"likes_count" : 1}});
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

// After update
> db.recipes.find({"title" : "Maple Smoked Salmon v2"}, {"title" : 1, "likes_count" : 1}).pretty()
{
        "_id" : ObjectId("5e878f5220a4f574c0aa56db"),
        "title" : "Maple Smoked Salmon v2",
        "likes_count" : 2
}

Update Arrays

Push

The push operator appends a specified value to an array.

// Given a Tacos with likes array : [1, 415] (refers to User IDs).
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "likes" : 1}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "likes" : [
                1,
                415
        ]
}

// Let's Push an other User ID to simulate a Like. 
> db.recipes.updateOne({"title" : "Tacos"}, {$push: { "likes":60 } } );
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

// After Push, User ID 60 added. In case the array we are looking to push to does not exists, the field and the values will not be inserted. 
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "likes" : 1}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "likes" : [
                1,
                415,
                60
        ]
}

Pull

The pull operator removes from an existing array all instances of a value or values that match a specified condition.

// Given a document with likes array. We would like to remove a user id. Example : User Id -> 415.
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "likes" : 1}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "likes" : [
                1,
                415,
                60
        ]
}

// Pull 415 from likes array
> db.recipes.updateOne({"title" : "Tacos"}, {$pull: { "likes":415 } } );
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

// After update
> db.recipes.find({"title" : "Tacos"}, {"title" : 1, "likes" : 1}).pretty();
{
        "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"),
        "title" : "Tacos",
        "likes" : [
                1,
                60
        ]
}

Delete Documents

Delete One Document

To delete a single document, use deleteOne().

// Given The following documents, we would like to delete a document where title is Tacos-2.
> db.recipes.find({}, {"title" : 1});

{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon v2" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a0039"), "title" : "Tacos" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a003a"), "title" : "Tacos-2" }

// Use delete one
> db.recipes.deleteOne({"title": "Tacos-2"});
{ "acknowledged" : true, "deletedCount" : 1 }

// After deletion
> db.recipes.find({}, {"title" : 1});
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon v2" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a0039"), "title" : "Tacos" }

Delete Many Documents

To delete many documents, use deleteMany().

// Given The following documents, we would like to delete documents where titles are Tacos, Maple Smoked Salmon v2.
> db.recipes.find({}, {"title" : 1});
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon v2" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5e5e9c470d33e9e8e3891b35"), "title" : "Tacos" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
{ "_id" : ObjectId("62a5304b5ea12a1ef17a0039"), "title" : "Tacos" }

// Delete 02 documents
> db.recipes.deleteMany({"title": "Tacos"}, {"title" : "Maple Smoked Salmon v2"});
{ "acknowledged" : true, "deletedCount" : 2 }

// After Deletion
> db.recipes.find({}, {"title" : 1});
{ "_id" : ObjectId("5e878f5220a4f574c0aa56db"), "title" : "Maple Smoked Salmon v2" }
{ "_id" : ObjectId("5e6fd805fa98021236426a24"), "title" : "Chicken Soft Tacos" }
{ "_id" : ObjectId("5e87856d07beb474c074c5ca"), "title" : "Brown Sugar Meatloaf" }
{ "_id" : ObjectId("5e877cba20a4f574c0aa56da"), "title" : "Pancakes" }
{ "_id" : ObjectId("5edf1d313260aab97ea0d589"), "title" : "Zucchini Brownies" }
{ "_id" : ObjectId("5edf1cd43260aab97ea0d588"), "title" : "Apple Pie" }
Clone this wiki locally