- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" } ] }
Advertisements