Jest to bardzo częsty wymóg, gdy filtr geograficzny i wyszukiwanie tekstu jest wymagane w jednym przypadku użycia, który niestety nie jest jeszcze bezpośrednio obsługiwany przez mongodb.
Poniższy kod wykorzystuje sterownik mangusty, najpierw filtruje dokumenty na podstawie lokalizacji (długość i szerokość geograficzna), a następnie dodaje kolejne filtry w oparciu o wyszukiwany termin.
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
});
W tym kodzie „post” jest coś schematu mangusta jak poniżej
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);
także dla obszaru wyszukiwania, istnieją inne opcje jak pudełka
var lowerLeft = [40.73083, -73.99756]
var upperRight= [40.741404, -73.988135]
query.where('loc').within().box(lowerLeft, upperRight)
Dla obu Geolokalizacja szukaj i szukaj tekstu do pracy, upewnij się, że masz indeks na pole i pole tekstowe. Więcej szczegółów tutaj. loc Search i text search
mogę użyć $ LT oraz $ gt operatorów, jeśli szerokość i długość geograficzna są przechowywane w tablicy ; coś w stylu - loc: [50.433234,20,220123] –