To perform a text search on the content field within the segments array in MongoDB and have scoring based on the relevance of the search, we'll need to configure a text index first, then use the $search operator. Below, I'll provide the steps and the MongoDB aggregation pipeline to achieve this.
Step 1: Create a Text Index
For MongoDB to perform text searches, you need to create a text index on the fields you're going to search. Since content is nested inside the segments array, you would create the index on segments.content.
Create the text index using the following command in MongoDB shell or from your MongoDB client:
db.yourCollectionName.createIndex({"segments.content": "text"})
Step 2: Write the Aggregation Pipeline
After the index is created, you can use an aggregation pipeline to perform a text search, score the documents based on text search relevance, and project the needed fields. Here’s how you can do it:
db.yourCollectionName.aggregate([
{
$match: {
$text: {
$search: "Olympic games", // Your search string
$caseSensitive: false,
$diacriticSensitive: false
}
}
},
{
$addFields: {
score: { $meta: "textScore" }
}
},
{
$project: {
segments: 1,
score: 1, // Include the text search score
_id: 0 // Optional: Exclude _id if not needed
}
},
{
$sort: {score: -1} // Optional: Sort the results by score
}
]);
Explanation:
- $match: Filters the documents to include only those that contain the text in the
content field of the segments array.
- $text: Specifies the text search parameters.
- $addFields: Adds a new field to each document, here used to include the text search score.
- $meta: "textScore" provides scoring based on the relevance of a text search.
- $project: Shapes the output document by including
segments, score, and optionally excluding _id.
- $sort: Orders the documents by score in descending order.
Notes:
- Replace
"Olympic games" with your actual search phrase.
- Adjust the
caseSensitive and diacriticSensitive options as necessary based on your search requirements.
- Make sure to replace
yourCollectionName with the actual name of your collection.
Using this setup, the aggregation pipeline leverages the full-text search capabilities of MongoDB to effectively perform text searches and score the documents based on the relevance of your search query within nested documents.