MongoDB
Beginner
1 min read
Text and Geospatial Indexes
Example
// Text index on multiple fields with weights
db.articles.createIndex(
{ title: "text", body: "text", tags: "text" },
{ weights: { title: 10, tags: 5, body: 1 }, name: "articleTextIdx" }
)
// $text search — find articles mentioning "mongodb performance"
db.articles.find(
{ $text: { $search: "mongodb performance" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
// Exclude a word with a minus prefix
db.articles.find({ $text: { $search: "mongodb -sql" } })
// 2dsphere index for GeoJSON
db.locations.createIndex({ coordinates: "2dsphere" })
// Insert a GeoJSON point
db.locations.insertOne({
name: "Central Park",
coordinates: { type: "Point", coordinates: [-73.9654, 40.7829] }
})
// $near — find locations within 1 km
db.locations.find({
coordinates: {
$near: {
$geometry: { type: "Point", coordinates: [-73.9654, 40.7829] },
$maxDistance: 1000
}
}
})