MongoDB query to filter only the logs containing the “work” word in the content


To filter the logs containing the word “work” , use aggregate() along with $filter. Let us first create a collection with documents −

> db.demo383.insertOne(
...    {
...       "ServerName":"Jboss",
...       "ServerLogs": [
...          {
...             "status":"Working"
...          },
...          {
...             "status":"Stop"
...          },
...          {
...             "status":"Worked"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b635422064be7ab44e7f1")
}

Display all documents from a collection with the help of find() method −

> db.demo383.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e5b635422064be7ab44e7f1"),
   "ServerName" : "Jboss",
   "ServerLogs" : [
      {
         "status" : "Working"
      },
      {
         "status" : "Stop"
      },
      {
         "status" : "Worked"
      }
   ]
}

Following is the query to filter −

> db.demo383.aggregate([
...    { "$addFields": {
...       "ServerLogs": {
...          "$filter": {
...             "input": "$ServerLogs",
...             "cond": {
...                "$ne": [
...                   { "$indexOfBytes": [
...                      { "$toUpper": "$$this.status" },
...                      { "$toUpper": "work" }
...                   ]},
...                   -1
...                ]
...             }
...          }
...       }
...    }}
... ])

This will produce the following output −

{
   "_id" : ObjectId("5e5b635422064be7ab44e7f1"), "ServerName" : "Jboss", "ServerLogs" : [
      { "status" : "Working" }, { "status" : "Worked" }
   ] 
}

Updated on: 02-Apr-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements