mongo-db
  1. mongo-db-text-search

Text Search for CRUD Operations in MongoDB

Text search is a powerful feature in MongoDB that allows you to search for specific words or phrases in your database. In this page, we will discuss how to perform text search in MongoDB using CRUD operations.

Syntax

The syntax for performing text search in MongoDB is as follows:

db.collection.find( { $text: { $search: "search string" } } )

Here, db.collection represents the collection in which you want to perform the search, and "search string" represents the word or phrase you want to search for.

Example

Suppose we have a collection named posts that contains documents with the following structure:

{
    "_id" : ObjectId("614f1baad8ad4fc743a70de0"),
    "title" : "Introduction to MongoDB",
    "body" : "MongoDB is a popular NoSQL database...",
    "tags" : [ "mongodb", "nosql", "database" ],
    "created_at" : ISODate("2021-09-24T07:34:50.659Z")
}

To perform text search for the word "MongoDB" in the posts collection, we can use the following query:

db.posts.find( { $text: { $search: "MongoDB" } } )

This query will retrieve all documents that contain the word "MongoDB" in the title or body fields.

Output

The output of the text search query will be a cursor containing all documents that match the search criteria.

Explanation

Text search in MongoDB uses the stemming technique to match words. This means that if you search for the word "running", MongoDB will also match documents that contain the words "run", "runner", or "ran".

By default, text search is case-insensitive and diacritic-insensitive. However, you can modify this behavior by specifying options in the text search query.

Use

Text search is useful for searching for specific words or phrases in your MongoDB database. It can be used to build search functionality for your application.

Important Points

  • Text search in MongoDB uses the $text operator to specify the search criteria.
  • Text search uses the stemming technique to match words.
  • By default, text search is case-insensitive and diacritic-insensitive.
  • You can modify the behavior of text search by specifying options in the query.

Summary

In this page, we discussed how to perform text search in MongoDB using CRUD operations. We covered the syntax, example, output, explanation, use, important points, and summary of text search in MongoDB. By using text search, you can search for specific words or phrases in your database and build search functionality for your application.

Published on: