What is the best way to convert and update document fields in MongoDB to GeoJSON format using Java?

I have a collection in mongodb that stores information about airports and I need to perform some Geospatial Queries.

One example document from this collection looks like this:

    {
            "_id" : ObjectId("528e8134556062edda12ffe6"),
            "id" : 6523,
            "ident" : "00A",
            "type" : "heliport",
            "name" : "Total Rf Heliport",
            "latitude_deg" : 40.07080078125,
            "longitude_deg" : -74.9336013793945,
            "elevation_ft" : 11,
            ...
    }

I want to transform all documents in the collection to have a structure like this:

    {
      "_id": ObjectId("528e8134556062edda12ffe6"),
      "id" : 6523,
      "ident" : "00A",
      "type" : "heliport",
      "name" : "Total Rf Heliport",
      "longitude_deg" : 17.27,
      "latitude_deg" : 52.22,
      "loc" : {
        "type" : "Point",
        "coordinates" : [
          17.27,
          52.22
        ]
      },
      ...
    }

The provided javascript code should achieve this transformation:

    var cursor = db.airports.find()

    cursor.forEach(function(input) {
      x = input.latitude_deg;
      y = input.longitude_deg;
      id = input._id;
      db.airports.update({"_id":id},{$set:{"loc":{"type":"Point","coordinates":[y,x]}}});
    });

However, I am struggling to create a Java program that accomplishes the same task. If anyone can provide guidance on how to solve this problem, it would be greatly appreciated.

Thank you in advance for your help and apologies for any language barriers!

Answer №1

To demonstrate this process, I have developed a sample application using the MongoDB Inc. driver (legacy) as well as the Asynchronous Java Driver.

In the case of the asynchronous driver, I showcase two different approaches: synchronous and asynchronous. The primary distinction between the two is that in the synchronous/legacy scenario, you must wait for each update to finish. On the other hand, with the asynchronous model, you can proceed with other tasks while document fetching and updates occur in the background.

HTH, Rob.

P.S. Full disclosure: I am involved with the Asynchronous Java Driver.

package geojson.sof20181050;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicLong;

...

...

Answer №2

Thank you for your response. I made a few changes to the legacy driver method, but encountered this error:


import java.io.IOException;
import java.util.ArrayList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;

public class Geo {

    public static void main(final String[] args) throws InterruptedException,
            IOException {

        MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);

        DB db = mongoClient.getDB("test");

        DBCollection coll = db.getCollection("airports2");


        try {
            int count = 0;
            for (final DBObject doc : coll.find()) {
                final Object id = doc.get("_id");
                final Number lat = Double.parseDouble(doc.get("latitude_deg").toString());
                final Number lon = Double.parseDouble(doc.get("longitude_deg").toString());

                final BasicDBObject query = new BasicDBObject();
                query.append("_id", id);

                final ArrayList coordinates = new ArrayList();
                coordinates.add(lon.doubleValue());
                coordinates.add(lat.doubleValue());
                final BasicDBObject geojson = new BasicDBObject("type", "Point");
                geojson.append("coordinates", coordinates);
                final BasicDBObject set = new BasicDBObject("loc", geojson);
                final BasicDBObject update = new BasicDBObject("$set", set);

                coll.update(query, update, false, false, WriteConcern.ACKNOWLEDGED);

                count += 1;
            }
            System.out.printf("Updated %d documents via the legacy driver.%n",
                    count);
        }
        finally {
            // Always close the client.
            mongoClient.close();
        }
    }

}

Although it works, the number of updated documents is different from db.airports.count(), which concerns me.

I am using the "airports" collection from this source.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Router: Navigating to a Route Becomes Problematic with useNavigate Hook

I am currently developing a React application that utilizes React Router for navigation purposes. One specific component named ShowNotes is causing some issues with the implementation of a "Delete" button, which is intended to redirect to the "/DeleteNotes ...

The functionality of Javascript Array.splice suddenly malfunctioned in my Angular application

While working on a project in Angular 4, I encountered a situation where I needed to batch through an array of ids. I would send the removed items to an Observable function, and upon the subscription returning, I would check the remaining array before loop ...

Why is the Node Express API not returning a response?

Recently, I successfully created a node-express API for my project. router.get('/getData', function(req, res) { let data = { title: 'Message Effectiveness – Bar Chart – 1Q', chartData: [ { title: 'Motivatin ...

HtmlUnit implementation encounters an Exception while retrieving page source code

Attempting to retrieve a dynamic page from a URL while using Java has presented some challenges. Initially, Selenium was used for this task, but the process was time-consuming due to the driver invocation time. To overcome this, HtmlUnit was explored as it ...

Organizing Sequential Data in MongoDb

Stored in my MongoDB database, I have Ignition Data organized against time in ascending order. It looks like this: 1. **V_no** **Ign** **time** 2. 001 On 1536721212 3. 001 On ...

What is the best way to transmit data as a reply from a Node.js server to an AJAX client?

Currently, I am utilizing a function to transmit data regarding an HTML element as an object: function postItem(input) { $.ajax({ type: "POST", url: "http://localhost:8080", data: input, success: function(message) { Hconsole.log(&a ...

Double trouble: Knockout validation errors displayed twice

Currently, I am using the knockout validation plugin to validate a basic form field. The validation functionality is working as expected, however, it seems to be displaying the same error message twice under the text box. The code snippet that I am using ...

Retrieve an image located outside of a container

I have multiple SVGs inside separate div elements. <div id="divA"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <rect x="10" y="10" height="130" width="500" style="fill: #000000"/> ...

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Retrieving the authenticated user post logging in through Firebase

After a user signs up, I want to send a verification email. I've written the code for it, but I'm facing an issue where trying to access the current user with Firebase in React Native always returns null. How can I resolve this? Below is the sig ...

Failed to establish Modbus TCP connection

Currently, I am utilizing the "Panasonic FP7" master PLC along with their official software "FPWIN GR7" to monitor data flow on my PC. However, since the software lacks certain functions, I have decided to develop a solution using nodeJS. Below is the code ...

Utilizing JavaScript to manage sections within a dropdown menu

When dealing with this particular HTML code, there is a feature where a list item includes options such as all, a, b, c, and d. If the user selects 'All', it should restrict them from choosing any other items. However, if they do not choose &apos ...

Converting a vector from global space to local space in three.js

I have an object in my scene that has been rotated. How do I go about translating a global vector into the local space of this rotated object so that they end up being rendered at the same position as the global vector? Let's say I have a cube that h ...

Guide to incorporating data provider values into testng extent-report version 2.41.2 (pertinent code snippets)

I utilized Dataprovider to pass test values and now I want these values to be displayed in my testNG extent report. With seven test cases running on various test values provided by the DataProvider, I am looking to have the extent report show the specific ...

Ember: Utilizing Models as Data Sources for CollectionViews

I am looking to integrate model data retrieved from an ajax request into the content of an Ember.CollectionView in order to create a list of items. My goal is to display a list showing the title from each object in the array received from the API. I am cur ...

Searching for multiple values in MongoDB using the `find` method

I need to search for specific data in my database: [case-file-header] => Array ( [filing-date] => 20130111) This is the code I am using: $cursor = $mongo->$db->$collection->find(array('case-file-header'=> ...

The custom configuration file for SailsJS does not seem to be loading properly

After following the documentation and advice on StackOverflow, I attempted to load custom configuration for my application. However, I faced a failure. I went ahead and created a new file named /config/application.js In this file, I added the followi ...

How can I effectively monitor entry and exit events in polygons for multiple locations using mongoDB?

In my current project, I am dealing with a large number of vehicles (approximately 2000) and multiple polygons stored in my database using MongoDB. These polygons represent various entities such as cities, countries, intersections, etc., totaling 4 differ ...

Query MongoDB to retrieve the highest performing store from a set of orders

Hello, I am relatively new to using MongoDB. In my database, I have two collections with the following structures: Order collection [ { id: 1, price: 249, store: 1, status: true }, { id: 2, price: 230, ...

Limit express to only allow AJAX requests

Currently working on an Express app where I aim to restrict access to the routes exclusively through AJAX requests. Aware that this involves using the X-Requested-With header, but uncertain of how to globally block other request types. Any suggestions or ...