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

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

Clone this wiki locally