Sorting, Indexing & Searching

Sorting Records

MongoDB provides the sort() method to sort the documents in a collection based on one or more fields. The method accepts an object specifying the fields to sort on and the sort order (ascending or descending).

// Sort documents in ascending order by the "age" field
db.collectionName.find().sort({ age: 1 })

// Sort documents in descending order by the "name" field
db.collectionName.find().sort({ name: -1 })

// Sort by multiple fields (first by "age" ascending, then by "name" descending)
db.collectionName.find().sort({ age: 1, name: -1 })

Creating and Deleting Text Indexes

MongoDB supports text indexes to perform text searches on string content. Text indexes can include any field whose value is a string or an array of string elements.

To create a text index:

db.collectionName.createIndex({ fieldName: "text" })

To delete a text index:

db.collectionName.dropIndex({ fieldName: "text" })

Text Search on a Collection

Once you've created a text index, you can perform text searches using the $text operator in the query.

// Search for documents where the "content" field contains the word "mongodb"
db.collectionName.find({ $text: { $search: "mongodb" } })

// Search for documents where the "content" field contains the phrase "mongodb query"
db.collectionName.find({ $text: { $search: "\"mongodb query\"" } })

Last updated

Was this helpful?