Volver a MongoDB Intermedio
Atlas Search y Búsqueda de Texto en MongoDB
Búsqueda de Texto (Auto-hospedado)
db.articulos.createIndex(
{ titulo: "text", cuerpo: "text", etiquetas: "text" },
{
weights: { titulo: 10, etiquetas: 5, cuerpo: 1 },
name: "idx_texto",
default_language: "spanish"
}
)
// Buscar con puntuación de relevancia
db.articulos.find(
{ $text: { $search: "mongodb rendimiento" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
// Búsqueda de frase exacta: "texto exacto"
// Exclusión: término -excluir
Atlas Search (Nube — Motor Lucene)
db.peliculas.aggregate([
{
$search: {
index: "default",
text: {
query: "ciencia ficción",
path: ["titulo", "trama"],
fuzzy: { maxEdits: 1 } // tolerancia a errores tipográficos
}
}
},
{ $limit: 10 },
{
$project: {
titulo: 1,
anio: 1,
score: { $meta: "searchScore" }
}
}
])
Atlas Search — Consultas Compuestas
db.productos.aggregate([
{
$search: {
compound: {
must: [
{ text: { query: "laptop", path: "nombre" } }
],
should: [
{ range: { path: "precio", lte: 1000 } }
],
filter: [
{ equals: { path: "enStock", value: true } }
]
}
}
}
])
Atlas Search — Autocompletado
// Definición de índice en la UI de Atlas:
// { "mappings": { "fields": { "nombre": [{ "type": "autocomplete" }] } } }
db.productos.aggregate([
{
$search: {
autocomplete: {
query: "lapt",
path: "nombre",
tokenOrder: "sequential"
}
}
},
{ $limit: 10 },
{ $project: { nombre: 1, _id: 0 } }
])
Atlas Search — Facetas
db.productos.aggregate([
{
$searchMeta: {
facet: {
operator: { text: { query: "laptop", path: "nombre" } },
facets: {
categoria: {
type: "string",
path: "categoria",
numBuckets: 5
},
rangoPrecio: {
type: "number",
path: "precio",
boundaries: [0, 100, 500, 1000],
default: "otro"
}
}
}
}
}
])
Búsqueda Multilingüe
// Índice con analizador en español (stemming correcto)
db.articulos.createIndex(
{ contenido: "text" },
{ default_language: "spanish" }
)
// En Atlas Search usar analyzer: "lucene.spanish"