- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" } ] }
- Related Articles
- MongoDB query to update a MongoDB row with only the objectid
- MySQL query to display only the records that contains single word?
- Get only the FALSE value with MongoDB query
- Filter documents in MongoDB using simple query?
- MongoDB query to filter by several array elements?
- MongoDB query to fetch only the “Name” field based on roles?
- How to work with variables in MongoDB query
- How to remove only the first word from columns values with a MySQL query?
- MongoDB query to filter object where all elements from nested array match the condition
- MongoDB query to find records with keys containing dots?
- MongoDB query to return only embedded document?
- MongoDB query to update only certain fields?
- MongoDB query to get only distinct values
- How to work Date query with ISODate in MongoDB?
- MongoDB query to return only specific fields (phone numbers) in the form of an array?

Advertisements