JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

A query similar to the SQL LIKE statement in MongoDB

Author:JIYIK Last Updated:2025/04/29 Views:

MongoDB is a powerful NoSQL database server. It uses JSON-like documents with optional schema to store data.

Organizing data is always an essential task for developers as it plays the most critical role in the performance of the application. In MongoDB, you can LIKEfetch data using queries similar to SQL statements.

Creating a Database in MongoDB

We will use some dummy data in the examples in this tutorial. You can also create the database and execute the commands given below to insert the dummy data.

db={
    "colors": [
        {
            "id": 100,
            "color": "Pink"
        },
        {
            "id": 101,
            "color": "Purple"
        },
        {
            "id": 102,
            "color": "Black"
        },
        {
            "id": 103,
            "color": "Blue"
        }
    ]
}

db.collection.find()Methods in MongoDB

When searching in a MongoDB collection, the most critical part is a flexible and direct db.collection.find()method.

Using , you can easily query a collection of documents db.collection.find(),by passing it a few simple parameters and returning one .光标

游标is just a result set. We can iterate over it to manipulate or otherwise use 光标the pointed-to documents.

db.collection.find()A simple example of the method is shown below.

> db.colors.find()

Output:

Find Database

The above program returns all the documents in a collection. But this is very rare for production requirements.

You always need some filtered results from the database.

For example, if you want to get color: Pinkall the data containing . Execute the following query.

>  db.colors.find({color: "Pink"})

Output:

Find Database 2

The query using db.collection.find()the method is similar to the SQL LIKE statement in MongoDB

You can use regular expressions to search for documents in MongoDB. This will be similar to LIKEthe statement in SQL query.

Now that you are using .find()to query your collection, you can change your syntax slightly and start looking for matches based on words or phrases that may be partial matches in specific fields, similar to how SQL engines use LIKEthe operator.

This technique makes use of regular expressions (regex), which are text strings that define a search pattern. Several regular expression engines are written with different syntaxes, but the basic principle is the same.

At the most basic level, a regular expression is /a string of characters enclosed in a single slash ( ).

db.collection.find({
    "k": /pattern/
})

But currently, since shell regular expressions mongoplayground.netdon't work when querying, you can use the expression given below.

db.collection.find({
    "k": {
        "$regex": "pattern"
    }
})

For example, if you want to perform the same query as above using regular expressions and find out how many documents contain the color Pink, you can "Pink"replace the string with /Pink/.

Use db.collection.find()the method to search for a matching string anywhere

The first statement searches for all documents where the color name contains anywhere in the string Pink. The second statement searches for Blall records where the color name contains .

The SQL statement for this query:

select * from colors where color LIKE "%Pink%"

The MongoDB statement for this query:

db.colors.find({
    "color": {
        "$regex": "Pink"
    }
})

Output:

Query with Like

The MongoDB statement for this query:

db.colors.find({
    "color": {
        "$regex": "Bl"
    }
})

Output:

Query with Like 2

Using regular expressions instead of standard quoted strings, you can start looking for partial word or phrase matches.

Use the method with ^to db.collection.find()search for the starting characters of a matching string

This will match all Pstrings that begin with the characters . For example, the carrot symbol is used ^.

The SQL statement for this query:

select * from colors where color LIKE "P%"

The MongoDB statement for this query:

db.colors.find({
    "color": {
        "$regex": "^P"
    }
})

Output:

Query with Like 3

Use the method with $to db.collection.find()search for a matching end-of-string character

The dollar $sign matches a string that ends with a specific character.

The following example matches all kstrings ending with the characters .

The SQL statement for this query:

select * from colors where color LIKE "%k"

The MongoDB statement for this query:

db.colors.find({
    "color": {
        "$regex": "k$"
    }
})

Output:

Search with Like 4

Use db.collection.find()the method and isearch for matching strings in any case

By default the method searches case-sensitively. However, you can instruct the command to match characters in any case db.collection.findusing the -e option used below .ifind

The SQL statement for this query:

select * from colors where color LIKE BINARY "pink"

The MongoDB statement for this query:

db.colors.find({
    "color": {
        "$regex": "k$/i"
    }
})

Output:

Search with Like 5

This MongoDB tutorial article teaches you how to search a database in MongoDB similar to SQL LIKEstatements.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

List all collections in MongoDB Shell

Publish Date:2025/04/29 Views:156 Category:MongoDB

When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c

Querying for non-null values in MongoDB

Publish Date:2025/04/29 Views:139 Category:MongoDB

This MongoDB article will explain how to query for non-null values ​​in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers

Shutting down with code:100 error in MongoDB

Publish Date:2025/04/29 Views:53 Category:MongoDB

This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know

SELECT COUNT GROUP BY in MongoDB

Publish Date:2025/04/29 Views:74 Category:MongoDB

In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation

Differences between MongoDB and Mongoose

Publish Date:2025/04/29 Views:80 Category:MongoDB

This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s

Install MongoDB using Homebrew

Publish Date:2025/04/29 Views:161 Category:MongoDB

MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a

Create a MongoDB dump of the database

Publish Date:2025/04/29 Views:62 Category:MongoDB

In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t

Get the size of the database in MongoDB

Publish Date:2025/04/29 Views:88 Category:MongoDB

When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;

Grouping values by multiple fields with MongoDB

Publish Date:2025/04/29 Views:99 Category:MongoDB

MongoDB Group by Multiple Fields is used to group values ​​by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial