![filter in mongodb compass filter in mongodb compass](https://mydaytodo.com/wp-content/uploads/2021/01/Screen-Shot-2021-01-19-at-8.00.26-pm-1024x632.jpg)
This operator can be used to find for certain strings in the collection.
![filter in mongodb compass filter in mongodb compass](https://images.wallpapersden.com/image/download/compass-shells-sand_aGVnZW2UmZqaraWkpJRmZ2VlrWltZQ.jpg)
Pattern matching can be achieved by the $regex operator.Note: If the search is performed on a string which is greater than say 38,000 characters, it will not display the right results. Hence we have clearly shown that to fetch the last ‘n’ documents in the collection, we can first sort the documents in descending order and then use the limit clause to return the ‘n’ number of documents which are required. The output clearly shows that the last two documents in the collection are displayed. If the command is executed successfully, the following Output will be shown: Here we have set the limit clause (2), so it will fetch the last two documents. The -1 basically indicates to sort the documents in reverse order or descending order so that the last document becomes the first document to be displayed.Ģ) Then use the limit clause to just display the number of records you want.
#Filter in mongodb compass code#
Here in the below code we have used regex operator to specify the search criteria.ĭb.Employee.find().limit(2).forEach(printjson)ġ) When querying for the documents, use the sort function to sort the records in reverse order based on the _id field value in the collection. Let’ also assume that we have the following documents in our collection. Let’s assume that we have our same Employee collection which has the Field names of “Employeeid” and “EmployeeName”.
![filter in mongodb compass filter in mongodb compass](https://i.stack.imgur.com/9vB5A.png)
The following example shows how this can be done. The regex operator in MongoDB is used to search for specific strings in the collection. Using $regex operator for Pattern matching Fetching last ‘n’ documents from a collection.Pattern matching without the regex operator.Using $regex operator for Pattern matching.Hence, one can use regular expressions to assist in retrieving data based on pattern matching search values. Sometimes when retrieving documents in a collection, you may not know exactly what the exact Field value to search for. Regular expressions are used for pattern matching, which is basically for findings strings within documents.