Skip to content
Advertisement

How would I access the values of the coordinates through a NodeJS MongoDB query?

    "_id" : ObjectId("607ce141dfc52641ea652fb2"), 
    "Timestamp" : ISODate("2020-11-18T02:38:22.000+0000"), 
    "Class" : "Class A", 
    "MMSI" : 219022256, 
    "MsgType" : "position_report", 
    "Position" : {
        "type" : "Point", 
        "coordinates" : [
            54.572058, 
            11.928778
        ]
    }, 
    "Status" : "Under way using engine", 
    "RoT" : 0.0, 
    "SoG" : 0.0, 
    "CoG" : 264.6, 
    "Heading" : 207
}

Here is my query: const ships = await ais .aggregate( [{ $match: { MMSI: 219022256 } }, { $sort: { Timestamp: -1 } }], { allowDiskUse: true, } ) .project({ _id: 0 }) .limit(1) .toArray();

Advertisement

Answer

considering the returned values you have an Array of objects (JSON objects) at your disposal, so you would be able to use the informations of each object like so:

for(let i = 0; i < Ships.length; i++){
   console.log(Ships[i]["Position"]["Coordinates"]);
   let myCoordinates = Ships[i]["Position"]["Coordinates"];
   let lat = myCoordinates[0];
   let lon = myCoordinates[1];
   // Use the coordinates
}

Cheers!

Advertisement