What is the best way to save data in MONGO DB with Java programming language?

Creating a blog post feature in my web application has been an interesting journey. Initially, I relied on mysql as the database to store the posts entered in the text area of the blog as an object in JavaScript. The process involved sending this object to the Java server side, where I would execute MySQL queries to retrieve the object in a result set and save it in the database. However, I have now decided to transition to using mongoDB for the same purpose. While I have grasped the basics from various tutorials, putting that knowledge to practice in my application has proven to be a bit challenging. I am eager to understand how the object from the JS will be passed within the loop and the correct approach to querying to save the object. Similarly, if there is a need to send an object from the server side to JS, I would like to know the best way to do so.

Snippet of My Server-Side Code:

    public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("myblog");
    System.out.println("Connected");
    //creating a collection object, similar to a table in SQL
    DBCollection items = db.getCollection("items"); 
    System.out.println("Retrieved items collection");

   //manipulating documents using BasicDbObject        
    BasicDBObject query = new BasicDBObject();
    System.out.println("Mongo object created");

      //Cursor, similar to ResultSet in SQL
    DBCursor cursor = items.find();
    System.out.println("Retrieved items");
     while(cursor.hasNext()){
        System.out.println(cursor.next());
    } 

While I have been able to understand the functionalities of establishing a mongo connection, working with documents, collections, and cursors, I am now seeking guidance on how to effectively save the object received from JS into mongoDB. Any recommendations or suggestions would be greatly appreciated.

Answer №1

To update a document in MongoDB using Java, you can utilize the save method from the DBCollection class in the following manner:

while(cursor.hasNext()){
    DBObject doc = cursor.next();

    doc.put("name", "Leo-vin");

    items.save(doc);
}

The cursor.next() method retrieves an object of type DBObject, which is your BSONObject.

Tip:

To make modifications to a document (BSON), you can use the put method from the BSONObject class.

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

Ways to precisely define a matrix of type Integer[][] in a coding scenario

It's an easy question for someone skilled in this. Create a two-dimensional array named 'res' with some hard-coded values like the following: Integer[][] res = new Integer[][] {.....hard code some values here on 2 dim...} How can you modif ...

Tips for picking a drop-down option using Selenium

I'm having trouble selecting a value from the dropdown in the code provided above. public class Dropdown { public static void main(String[] args) { // TODO Auto-generated method stub // TODO Auto-generated method stub ...

Ensure that every route is prefixed with /api

Is there a way to set all routes accepted by Express to start with /api without explicitly defining it? Current: this.app.get('/api/endpoint-A', (req, res) => { return res.send('A'); }); this.app.get('/api/endpoint-B', ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

What is the best way to tackle the Vehicle Routing Problem using the HERE Maps API?

I've come across the FindSequence and FindPicukups APIs, but unfortunately, neither of them seem to work for multiple vehicles. Is there a way to leverage the Matrix API in conjunction with these APIs to solve this issue? Or perhaps there's anoth ...

Compose a generic step in jBehave

Could you provide the step method in jBehave for selecting an action on a panel using both parameter injection and parameterized scenarios? @When("I select action <actionText> on <panelTitle>") @Alias("I select action $actionText on $panelTitl ...

How can I dynamically adjust the stroke length of an SVG circle using code?

In my design project, I utilized Inkscape to create a circle. With the fill turned off, only the stroke was visible. The starting point was set at 45 degrees and the ending point at 315 degrees. After rotating it 90 degrees, here is the final outcome. < ...

Steps to send a prop value to a Vue.js SCSS file

I am trying to include the props (string) value in my scss file Within my component, I am using the nbColor prop with a value of 'warning'. I want to be able to use this value in my scss file where I have a class called .colorNb {color: color(nb ...

Keep track of the toggled state and prevent any flickering when the page is reloaded, all without the

After extensive searching, I couldn't find exactly what I needed. Therefore, I decided to utilize cookies to remember the toggled state of a div whether it's hidden or visible. However, I encountered an issue where there is flicker happening as t ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Warning: No automatic session available: Logical Sessions are exclusively compatible with server versions 3.6 and above

I am facing an issue while trying to run my Express application on Docker. The application has a dependency on MongoDB. I have created a compose file with the following configuration: version: '3' services: mongo: container_name: mongo ...

A problem encountered in specific JavaScript code

As a newcomer to JavaScript, I have encountered an issue while trying to run this script: <html> <head> <title>Exploring javascript functionalities</title> </head> <body> <p id="demo">I ...

Issues with JavaScript and CSS functionality not functioning correctly as expected

There seems to be an issue with the order of HTML elements in the following code. When I place the div with the class thumb-bar before the full-img div, the JavaScript functions correctly. However, if I switch their positions, the JavaScript functionalitie ...

Creating a seamless thread using AngularJS

I am working on a Spring MVC application that utilizes HTML and Angular on the client side. I have a method in my Angular controller that needs to run every 5 seconds. How can I achieve this using Angular? Thank you for your assistance. $scope.inspectio ...

Is there a way to retrieve an element based on its position within the webpage?

Issue at Hand: My current challenge involves extracting phone numbers from a webpage. Each phone number is concealed behind a button labeled "show contact info". The actual numbers are not visible in the dom until after the button is clicked. Upon clicking ...

Webpack attempting to load build.js from a nested folder

I am in the process of setting up a Vue app with Vuetify and Vue Router. Everything works fine when I load the base URL "/", and I can easily navigate to /manage/products. However, if I try to directly access /manage/products by typing it into the address ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

When loading a page in NodeJS and Express, there are no initial displays, but upon refreshing the page, all data is successfully retrieved

Struggling to solve this issue that has been lingering for a while. I'm currently working on a project where a remote JSON file is loaded into memory, parsed, and the results are displayed on the page (using pug). Everything seems to be working fine ...

Dealing with VueJS - Sharing an array of data from a child to a parent component using v-model

I am facing an issue in emitting data (array) from a child component to a parent component using v-model. However, when the parent component is created, my console.log does not work. I am hesitant to work with Vuex as I am still a beginner. Here is my chi ...

Having trouble with Angular's ng-class performance when dealing with a large number of elements in the

I've encountered a performance issue while working on a complex angular page. To demonstrate the problem, I've created a fiddle that can be viewed here. The main cause of the performance problem lies in the ng-class statement which includes a fu ...