I have the following document in my MongoDB collection, which I would like to be able to do a query that check if point that is provided by the user is inside a bbox array that is stored in the collection.
{
"type": "Feature",
"properties": {
"place_id": 298104298,
"osm_type": "relation",
"osm_id": 80500,
"display_name": "Australia",
"place_rank": 4,
"category": "boundary",
"type": "administrative",
"importance": 0.8521350639151115,
"address": {
"country": "Australia",
"country_code": "au"
}
},
"bbox": [
72.2461932,
-55.3228175,
168.2261259,
-9.0880125
]
}
What I would like to do is a geoIntersect or geoWithin query.
for example:
[{
$match: {
bbox: {
$nearSphere: {
$geometry: {
type: 'Point',
coordinates: [
-73.9667,
40.78
]
}
}
}
}
}]
I have also tried
[{
$project: {
geometry: 0
}
}, {
$match: {
bbox: {
$geoWithin: {
$box: [
[
-73.9667,
40.78
],
[
40.78,
-73.9667
]
]
}
}
}
}]
However that did return results but wrong results the geo location should return NULL as the location is Antarctic Ice shield, Antarctica - (-73.9667,40.78)
Related
I have a column in a MongoDB collection with location stored as string pair values:
geometry:"POINT (72.548355 23.042458)"
I need to create a geometry field which works with MongoDB's spatial queries. Something which is in this format:
"geometry": {
"type": "Point",
"coordinates": [72.548355, 23.042458]
},
Please help. I need to run this for billions of entries in the collection. So an optimized solution will be extremely helpful. Thanks in advance
db.collection.update({},
[
{
"$set": {
"geometry": {
$let: {
vars: {
"arr": { $split: [ "$geometry", " " ] }
},
in: {
"type": {
$concat: [
{ $toUpper: { $substr: [ { $first: "$$arr" }, 0, 1 ] } },
{ $toLower: { $substr: [ { $first: "$$arr" }, 1, { $strLenCP: { $first: "$$arr" } } ] } }
]
},
"coordinates": [
{
$toDouble:{
$ltrim: {
input: { $arrayElemAt: [ "$$arr", 1 ] },
chars: "("
}
}
},
{
$toDouble:{
$rtrim: {
input: { $arrayElemAt: [ "$$arr", 2 ] },
chars: ")"
}
}
}
]
}
}
}
}
}
],
{ "multi": true })
mongoplayground
In mongo DB I have a collection dealing with buildings ("centros") that contain devices ("dispositivos") and those devices contain sensors ("sensores").
I am trying to update one of those sensors.
Buildings are identified by their "_id", devices by their "uid" and sensors by their "variable name" ("variable").
I have already tried following some examples found on StackOverflow, but have not succeeded.
This is my approximation:
db.collection.update({
"uid": "e898b585-d855-4017-9fe4-0644360f9d1b"
},
{
"$set": {
"dispositivos.$[dispositivo].sensores.$[sensor]": {
"variable": "Plutonio",
"unidad": "yuyuyuyuuyu"
}
}
},
{
"multi": false,
"upsert": false,
arrayFilters: [
{
"dispositivo.uid": "e898b585-d855-4017-9fe4-064386kkkkkk",
"sensor.variable": "intensidad"
}
]
})
But it gives me the following error:
fail to run update: multiple write errors: [{write errors: [{Error parsing array filter :: caused by :: Expected a single top-level field name, found 'sensor' and 'dispositivo'}]}, {<nil>}]
There you have a live sample: https://mongoplayground.net/p/KrWw2WxkSch
This is my collection sample:
[
{
"uid": "e898b585-d855-4017-9fe4-0644360f9d1b",
"nombre": "Colegio Rio Piles",
"tipo": "Colegio",
"direccion": {
"calle": "Paseo Dr. Fleming, 1109",
"codigoPostal": "33204",
"municipio": "Gijon",
"provincia": "Asturias",
"ubicacion": {
"latitud": "43.5351406",
"longitud": "-5.6345379"
}
},
"horario": {
"apertura": "09:00",
"cierre": "22:00"
},
"dispositivos": [
{
"uid": "e898b585-d855-4017-9fe4-064386055555",
"descripcion": "",
"tipo": "ANALIZADOR_RED",
"adquisicion": "30s",
"sensores": [
{
"variable": "voltaje",
"unidad": "V"
},
{
"variable": "intensidad",
"unidad": "A"
}
]
},
{
"uid": "e898b585-d855-4017-9fe4-064386kkkkkk",
"descripcion": "",
"tipo": "CONTADOR_AGUA",
"adquisicion": "30s",
"sensores": [
{
"variable": "caudal",
"unidad": "l/s"
}
]
}
]
}
]
Thanks JOE for the help. That is the solution:
db.collection.update({
"uid": "e898b585-d855-4017-9fe4-0644360f9d1b"
},
{
"$set": {
"dispositivos.$[dispositivo].sensores.$[sensor]": {
"variable": "Plutonio",
"unidad": "yuyuyuyuuyu"
}
}
},
{
"multi": false,
"upsert": false,
arrayFilters: [
{
"dispositivo.uid": "e898b585-d855-4017-9fe4-064386055555"
},
{
"sensor.variable": "intensidad"
}
]
})
Each array filter should be its own object in the array, like
arrayFilters: [
{
"dispositivo.uid": "e898b585-d855-4017-9fe4-064386kkkkkk"
},
{
"sensor.variable": "intensidad"
}
]
I want to find out which Polygon from a collection, contains the most points from another collection.
I’m using one collection with restaurant data (points) and one with the neighborhood data (polygons)
Both collections are provided by mongodb:
https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/neighborhoods.json
https://raw.githubusercontent.com/mongodb/docs-assets/geospatial/restaurants.json
Neighborhood document:
{
"_id": {
"$oid": "55cb9c666c522cafdb053a1a"
},
"geometry": {
"coordinates": [
[
[
-73.9443878859649,
40.70042452378256
],
[
-73.94424286147482,
40.69969927964773
],
[
-73.94193078816193,
40.70072523469547
],…
]
],
"type": "Polygon"
},
"name": "Bedford"
}
Restaurant document
{
"_id" : { "$oid" : "55cba2476c522cafdb053add" },
"location" : {"coordinates":[-73.856077,40.848447] , "type":"Point" },
"name" : "Morris Park Bake Shop"
}
Here an example to find out all restaurants within a single district:
Select one neighborhood (polygon) by a given point ($geoIntersects)
var neighborhood = db.neighborhoods.findOne(
{
geometry:
{
$geoIntersects:
{
$geometry: { type: "Point", coordinates: [ -73.93414657, 40.82302903 ] }
}
}
}
)
Find out how many restaurants are in this neighborhood
db.restaurants.find( { location: { $geoWithin: { $geometry: neighborhood.geometry } } } ).count()
My question:
Which neighborhood contains the most restaurants?
In my MongoDB aggregation query, I am using $lookup to join my offers collection with outlet collection. But, in my "outlets" collection, I have one field named location and i want the query to sort the results from closest to farthest of that location. So, how to use $geoNear with $lookup, any help would be appreciated? Below is my query:
db.offers.aggregate([
{
$geoNear: {
near: {
type: "Points",
coordinates: [
22,
77
]
},
distanceField: "distance",
maxDistance: 5000,
spherical: true
}
},
{
$match: {
$and: [
{
'totalDiscount': {
$gt: 40
}
},
{
'totalDiscount': {
$lt: 60
}
}
]
}
},
{
$unwind: "$storeUuid"
},
{
$lookup: {
from: "outlets",
localField: "storeUuid",
foreignField: "uuid",
as: "store"
}
},
{
$project: {
_id: 0,
location1: {
$arrayElemAt: [
"$store.location",
0
]
}
}
},
{
$addFields: {
'location.latitude': {
$ifNull: [
{
$arrayElemAt: [
"$location1.coordinates",
1
]
},
0
]
},
'location.longitude': {
$ifNull: [
{
$arrayElemAt: [
"$location1.coordinates",
0
]
},
0
]
}
}
},
{
$sort: {
location: 1
}
}
])
Offer data model
{
"offerId": "6e9d595a-16ad-4c6c-93d9-a7edc2bbb56f",
"brandUuid": [
"5b198438-8b4c-46f0-8cc2-6a938cb41d8e"
],
"storeUuid": [
"33ca653e-2af0-4728-b4a0-1178565c2b40",
"1b383916-8856-4f5a-8761-4bd4585e1d71"
],
"totalDiscount": 50
}
Outlet data model
{
"uuid": "20389cc1-2791-4d7b-a603-75b7abd6d48a",
"location": {
"type": "Point",
"coordinates": [
77.6504768,
12.9176082
]
}
},
EDIT: Based on Waqas Noor's answer
Actual Result
{
"offers": [
{
"uuid": "33ca653e-2af0-4728-b4a0-1178565c2b40",
"distance": 2780.7979952350124,
"offerId": "6e9d595a-16ad-4c6c-93d9-a7edc2bbb56f"
},
{
"uuid": "b4768792-a927-4d65-91a3-8ad67ad217b2",
"distance": 3930.1660094190306,
"offerId": "4f71fe98-cb43-4134-b360-b32017981de1"
},
{
"uuid": "1dbac2d2-b326-4d6d-8d74-9df99f35f542",
"distance": 3973.3702922423313,
"offerId": "070b916c-dd4d-42b4-b886-74318f576ffb"
},
{
"uuid": "20389cc1-2791-4d7b-a603-75b7abd6d48a",
"distance": 4107.770111767324,
"offerId": "0f037c18-a58f-4b03-b0f4-db8e2d971b74"
},
{
"uuid": "20389cc1-2791-4d7b-a603-75b7abd6d48a",
"distance": 4107.770111767324,
"offerId": "070b916c-dd4d-42b4-b886-74318f576ffb"
},
{
"uuid": "2f968cfa-1bf1-4344-bc73-998f4974f58a",
"distance": 4165.187832520325,
"offerId": "4f71fe98-cb43-4134-b360-b32017981de1"
},
{
"uuid": "3cc1461f-f29b-4744-a540-69d24ebb98a8",
"distance": 4262.636071210964,
"offerId": "0f037c18-a58f-4b03-b0f4-db8e2d971b74"
},
{
"uuid": "3cc1461f-f29b-4744-a540-69d24ebb98a8",
"distance": 4262.636071210964,
"offerId": "070b916c-dd4d-42b4-b886-74318f576ffb"
},
{
"uuid": "1b383916-8856-4f5a-8761-4bd4585e1d71",
"distance": 4361.786323018647,
"offerId": "6e9d595a-16ad-4c6c-93d9-a7edc2bbb56f"
},
{
"uuid": "7af0e1f8-d4d6-4700-adea-1df07a029f56",
"distance": 4564.666204168865,
"offerId": "8bbb5e27-89ff-417f-8312-f70e3911cb4c"
}
]
}
Expected Result
{
"offers": [
{
"uuid": "33ca653e-2af0-4728-b4a0-1178565c2b40",
"distance": 2780.7979952350124,
"offerId": "6e9d595a-16ad-4c6c-93d9-a7edc2bbb56f"
},
{
"uuid": "b4768792-a927-4d65-91a3-8ad67ad217b2",
"distance": 3930.1660094190306,
"offerId": "4f71fe98-cb43-4134-b360-b32017981de1"
},
{
"uuid": "1dbac2d2-b326-4d6d-8d74-9df99f35f542",
"distance": 3973.3702922423313,
"offerId": "070b916c-dd4d-42b4-b886-74318f576ffb"
},
{
"uuid": "20389cc1-2791-4d7b-a603-75b7abd6d48a",
"distance": 4107.770111767324,
"offerId": "0f037c18-a58f-4b03-b0f4-db8e2d971b74"
},
{
"uuid": "2f968cfa-1bf1-4344-bc73-998f4974f58a",
"distance": 4165.187832520325,
"offerId": "4f71fe98-cb43-4134-b360-b32017981de1"
},
{
"uuid": "3cc1461f-f29b-4744-a540-69d24ebb98a8",
"distance": 4262.636071210964,
"offerId": "0f037c18-a58f-4b03-b0f4-db8e2d971b74"
},
{
"uuid": "1b383916-8856-4f5a-8761-4bd4585e1d71",
"distance": 4361.786323018647,
"offerId": "6e9d595a-16ad-4c6c-93d9-a7edc2bbb56f"
},
{
"uuid": "7af0e1f8-d4d6-4700-adea-1df07a029f56",
"distance": 4564.666204168865,
"offerId": "8bbb5e27-89ff-417f-8312-f70e3911cb4c"
}
]
}
1) You need to have 2dsphare index on outlet collection on field location.
You can make one using:
db.outlet.createIndex( {location : "2dsphere" } )
2) You have to run aggregation on outlet collection since it contains the location field and you can only use $geoNear as first stage of pipeline.
Your query will look like
db.outlet.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ 77.6504768,
12.9176088] },
distanceField: "distance",
includeLocs: "location",
spherical: true
}
}])
3) Then you can combine the offers in your outlets using $lookup Operator.
Your complete query will look something like
db.outlet.aggregate([
{
$geoNear: {
near: {
type: "Point", coordinates: [77.6504768,
12.9176088]
},
distanceField: "distance",
includeLocs: "location",
spherical: true
}
},
{ $project: { uuid: 1, distance: 1 } },
{
$lookup: {
from: "offers",
localField: "uuid",
foreignField: "storeUuid",
as: "offers"
}
},
{ $unwind: '$offers' },
{
$match: {
'offers.totalDiscount': {
$gt: 40,
$lt: 60
}
}
},
{ $sort: { distance: -1 } }
])
I have user collection:
{
"_id": { "$oid" : "514C438232F5699004000014" },
"gender": 1,
"loc": {
"coordinates": [
0.777084,
0.701690
],
"type": "Point"
},
"name": "H1",
"radius": 1
},
{
"_id": { "$oid" : "514C438232F5699004000014" },
"gender": 1,
"loc": {
"coordinates": [
0.677084,
0.701690
],
"type": "Point"
},
"name": "H2",
"radius": 0.4
}
db.user.ensureIndex( { loc : "2dsphere" } )
I need to write query and use radius property from collection's row ( "radius": 1 ) in find query like this:
db.user.find( { loc: { $geoWithin :{ $centerSphere : [ [0.7, 0.7 ] , radius ]} } } )
But mongo returns:
JavaScript execution failed: ReferenceError: radius is not defined
I have tried db.user.find( { loc: { $geoWithin :{ $centerSphere : [ [0.7, 0.7 ] , this.radius ]} } } )
I think you have to do a two way query. First fetch the radius of a given user, then search for all location within this radius.