Questo è un requisito molto comune in cui è richiesto filtro geografico e ricerca di testo in un caso d'uso che purtroppo non direttamente supportato dal mongodb ancora.
Il codice riportato di seguito utilizza il driver mangusta, filtra i documenti per primi in base alla posizione (longitudine e latitudine) e quindi ulteriori filtri in base al termine cercato.
var area = {
center: [51, -114], //lng = 51 and lat = -114
radius: 100,
unique: true //this option is deprecated from MongoDB 2.6 on as mongodb no longer returns duplicate results
};
var query = Post.where('loc').within().circle(area) //Step 1: filter based on location
//Step 2: Next filter on the basis of searched text
.where({
$text: {
$search: <searchTerm>
}
}, {
score: {
$meta: 'textScore'
}
})
//Step 3: Filter any document fields that should not be returned in the result
.select({
"val1": 0,
"val2": 0
});
//Execute the query
query.exec(function (err, result) {
if (err) {
//return error in the response
}
//return result object in the response
});
In questo codice "Post" è un qualcosa di schema mangusta come qui di seguito
var PostSchema = new Schema({
title: String,
description: String,
loc: {
type: [Number], // [<longitude>, <latitude>]
index: '2d' // create the geospatial index
}
//some other fields
}
module.exports = mongoose.model('Post', PostSchema);
Anche per l'area di ricerca, ci sono altre opzioni disponibili come la scatola
var lowerLeft = [40.73083, -73.99756]
var upperRight= [40.741404, -73.988135]
query.where('loc').within().box(lowerLeft, upperRight)
Per entrambi Geolocalizzazione ricerca e ricerca di testo per lavorare, assicurarsi di avere indice sul campo loc e sul campo di testo. Maggiori dettagli qui. loc Search e text search
posso usare $ operatori lt e $ GT se la latitudine e la longitudine sono memorizzati in un array ; qualcosa come- loc: [50.433234,20,220123] –