Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$filtercreates a new array containing only matching elements -
$indexOfBytesreturns the byte position of substring (-1 if not found) -
$toUpperensures case-insensitive matching -
$ne: -1keeps 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.
Advertisements
