MongoDB doesn’t Contain a String query

MongoDB does not Contain a String

Today in this article, we will see how to search records in MongoDB does not contain a string.

We will learn to search a string and match documents based on case-sensitive and insensitive searches in this informative article.

Multiple approaches are covered, including using a like query or regex query.

We will see multiple approaches to achieve the same like using a like query or regex query etc.

Today in this article, we will cover below aspects,

Let’s take the example below to learn the query.

I have a sample MongoDB document below in one of the collections.

[
  {
    "_id": "5db5a4476997188b2722c820",
    "Name": "Design Patterns",
    "Price": 54.93,
    "Category": "Computers",
    "Author": "Ralph Johnson"
  },
  {
    "_id": "5ff50353a29ce9564c2724e2",
    "Name": "Design Patterns",
    "Price": 54.93,
    "Category": "Computers",
    "Author": "Mike Casper"
  },
  {
    "_id": "5ff503cda29ce9564c2724e3",
    "Name": "Design Patterns",
    "Price": 54.93,
    "Category": "Computers",
    "Author": "Julia Robert"
  },
 {
    "_id": "5f34a2430c3ca98a8c9052d2",
    "Name": "Design Patterns",
    "Price": 54.93,
    "Category": "Computers",
    "Author": "Mike Johnson"
  }
]

MongoDB does not Contain a String

Let’s build a MongoDB query using a regex for getting documents that don’t contain a String.

Author names where the name contains a word like “John” or “john” for the Author field value.

Here we are trying to match “John” or “john” could be contained at the start or last or in the middle or anywhere else of Author names.

MongoDB does not Contain a String – Case sensitive

Command

{ Field Name : {'$regex' : '^((?!Field Value).)*$'}}

Example

db.Books.find( { {Author:{'$regex' : '^((?!John).)*$'}} )

Mongo Query Result :

mongodb not equal, mongodb check if field is string, mongodb regex not contains, mongodb array does not contain, mongodb not string, not in mongodb aggregate, mongodb match string, nor in mongodb,

MongoDB does not Contain a String – Case insensitive

Command

{Field Name :{'$regex' : '^((?!Field Value).)*$', '$options' : 'i'}}

Example

{Author: {$regex: '^((?!John).)*$',$options: 'i'}}

References :


Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *