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

To filter logs containing the word "work" in MongoDB, use the $filter operator with $indexOfBytes to perform case-insensitive substring matching within an aggregation pipeline.

Syntax

db.collection.aggregate([
    {
        "$addFields": {
            "arrayField": {
                "$filter": {
                    "input": "$arrayField",
                    "cond": {
                        "$ne": [
                            {
                                "$indexOfBytes": [
                                    { "$toUpper": "$$this.field" },
                                    { "$toUpper": "searchWord" }
                                ]
                            },
                            -1
                        ]
                    }
                }
            }
        }
    }
]);

Sample Data

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

Display All Documents

db.demo383.find().pretty();
{
    "_id": ObjectId("5e5b635422064be7ab44e7f1"),
    "ServerName": "Jboss",
    "ServerLogs": [
        {
            "status": "Working"
        },
        {
            "status": "Stop"
        },
        {
            "status": "Worked"
        }
    ]
}

Filter Logs Containing "work"

db.demo383.aggregate([
    {
        "$addFields": {
            "ServerLogs": {
                "$filter": {
                    "input": "$ServerLogs",
                    "cond": {
                        "$ne": [
                            {
                                "$indexOfBytes": [
                                    { "$toUpper": "$$this.status" },
                                    { "$toUpper": "work" }
                                ]
                            },
                            -1
                        ]
                    }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e5b635422064be7ab44e7f1"),
    "ServerName": "Jboss",
    "ServerLogs": [
        { "status": "Working" },
        { "status": "Worked" }
    ]
}

How It Works

  • $filter creates a new array containing only matching elements
  • $indexOfBytes returns the byte position of substring (-1 if not found)
  • $toUpper ensures case-insensitive matching
  • $ne: -1 keeps elements where the substring is found

Conclusion

Use $filter with $indexOfBytes for substring matching in MongoDB arrays. This approach provides case-insensitive filtering and works effectively for log content analysis.

Updated on: 2026-03-15T02:45:27+05:30

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements