{{announcement.body}}
{{announcement.title}}

MongoDB Pipelines With Examples

DZone 's Guide to

MongoDB Pipelines With Examples

In this article, look at a few examples of writing queries with pipeline by explaining each query in detail.

· Database Zone ·
Free Resource

If you are a beginner to MongoDB, writing queries using pipelines could be a little tricky. I personally took some time to understand how each part in the pipeline works and how to write them effectively. In this article, I present a few examples of writing queries with pipeline by explaining each query in detail. 

Let's take a collection of documents where each document tracks articles written by different authors on different categories. Each document tracks the task ID assigned to the author for tracking his/her progress and the articles written by him/her with the status of each article whether completed or pending. We have various authors writing different articles on categories like devops, testing, etc. Here, we store the document in the collection based on category and article status. The example structure is as below.

{
        "_id" : ObjectId("5c109c596f3e51a8b19a6455"),
        "taskid" : 3456,
        "section" : "testing",
        "author" : "Jefferey Dunn's",
        "documents" : [
                {
                        "name" : "Moving From Manual to Automated Testing at a Small Company",
                        "status" : "incomplete"
                },
                {
                        "name" : "Things You Need to Know About API Testing",
                        "status" : "incomplete"
                },
                {
                        "name" : "All Things You Need To Know About Exhaustive Testing ",
                        "status" : "completed"
                }
        ]
}

The complete data used in this tutorial can be found here https://gist.github.com/adityacs/3e095187b43bf27466e2cc4acbec360e.

Now let's look at the examples.

Example 1: Query: Total count of all articles in completed status

db.article.aggregate([
    {"$unwind": "$documents"},
    {
        "$match": {
            "documents.status": "completed"
        }
    },
    {
      $count: "completed_documents"
    }
])

unwind: As the name says, this will deconstruct the values in array as a separate document with other fields in the document (mongodb document).  In this example, we have documents array and unwind will uncurl each value as shown below.

{"taskid": "1234", "section": "devops", "author": "Karissa Peth", "documents": {"name": "Getting Started With Monitoring for Developers", "status": "completed"}
{"taskid": "1234", "section": "devops", "author": "Karissa Peth", "documents":{"name": "Intro to Jenkins Pipelines and Publishing Over SSH","status": "pending"}

Here, we get each value of the array along with other fields as single document. 

match: Once, we get the documents then we can find the matching documents based on our query. Here we are querying for all matching documents with status completed.

count: This counts the number of documents returned after the match and we are assigning it to the variable  completed_documents .

The result after you run this query would be as below.

 { "completed_documents" : 3 } 

Example 2: Query:  Count of all articles in completed status, group by section

db.article.aggregate([
    {"$unwind": "$documents"},
    {
        "$match": {
            "documents.status": "completed"
        }
    },
   {    
       "$group": {
    "_id": "$section",
    "count": {"$sum": 1}
}
},
    {
        "$project": {
            "_id": 0,
            "section": "$_id",
            "count": 1
        }
    }
])

unwind and match works the same way as explained in Example 1. You can see here that we have made use of $group aggregation. $group will group the documents based on a specified selection.

_id: This is the key that holds the distinct values. In this example, it holds the distinct values of a section. 

count: Count is the accumulator operator. In our example, we are adding +1 to all documents with different sections i.e. if the document is having "testing" as section it will count +1 for "testing" and if the document is having "devops" as section, +1 is counted for "devops" separately. Each section will have a separate counter. 

The result of the query will be as below.

{ "_id" : "testing", "count" : 2 }
{ "_id" : "devops", "count" : 3 }

Now, if we like to rename the _id value with some custom name. We can use a project operator. In this example, we are projecting _id value to section field and count we are projecting as it is.

One thing to notice here is that we are making  _id:0 , which removes the _id fields from the final result. The below results show final result with _id field and without _id field.

{ "count" : 2, "section" : "testing" }
{ "count" : 3, "section" : "devops" } 

Without making _id as zero, result will be as below.

{ "_id" : "testing", "count" : 2, "section" : "testing" }
{ "_id" : "devops", "count" : 3, "section" : "devops" } 

Example 3: Query: Get an array of documents belonging to a section

db.article.aggregate([
    {"$unwind": "$documents"},
    {    
       "$group": {
    "_id": "$section",
   "docs": {"$push": "$documents.name"}
}
},
    {
        "$project": {
            "_id": 0,
            "section": "$_id",
            "docs": 1
        }
    }
])

In this example, we are grouping all documents by section and then we are using the $push operator to push the documents name to docs array. Using $project we are removing _id from final result and instead, we are mapping _id to section field which displays the value of _id as section. 

The final result will be as below:

{
        "docs" : [
                "Improving Your Regression Testing Projects Through Automation ",
                "Getting Started With Monitoring for Developers",
                "Intro to Jenkins Pipelines and Publishing Over SSH"
        ],
        "section" : "devops"
}
{
        "docs" : [
                "Moving From Manual to Automated Testing at a Small Company",
                "Things You Need to Know About API Testing",
                "All Things You Need To Know About Exhaustive Testing "
        ],
        "section" : "testing"
}

Hopefully, the above examples will give a good heads up for a beginner. Please feel free to comment and ask questions.



If you enjoyed this article and want to learn more about MongoDB, check out this collection of tutorials and articles on all things MongoDB.

Topics:
mongodb ,mongodb tutorial ,tutorial ,database ,database tutorial ,json

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}