What could be causing the mysterious error in Mongo DB?

I am struggling with implementing Mongo DB in Java as a beginner. Despite going through several slides, I find myself confused about its functionality. When I tried running a small Java program using MongoDB, it didn't work as expected.

This is my Java code:

public class MongoDbTesting {

    public void connectingMongo() throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("todo");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items"); 
    System.out.println("items got");

    //to work with document we need basicDbObject       
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");
    //insert in mongo
    query.put("priority", "highest");
    items.insert(query);
    System.out.println("Inserted");     
      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
    //print highest priority items

    while(cursor.hasNext()){
        System.out.println(cursor.hasNext());
    }   
    } 
    }

The output displayed is: it continuously prints:

true true true true true true true true true true true true true true true true true true true true true true

As I am unable to figure out what is happening, I need assistance in inserting data into the collection "items". Also, if anybody can guide me on how to use MongoDB in Java, that would be greatly appreciated. Having a good understanding of MySQL, I'm finding it hard to transition my knowledge to MongoDB and understand queries like "query.put". Any suggestions?

Answer №1

By neglecting to invoke cursor.next() within the while loop, you inadvertently created an endless cycle.

Answer №2

It is recommended to utilize:

System.out.println(cursor.next());

instead of

System.out.println(cursor.hasNext());

...

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

What steps should I take to make my include function operational?

As I develop a website for our entertainment company, I encounter language translation issues. Due to our diverse clientele, I implemented a multilingual feature on the site. However, during testing, all the text appeared blank. I suspect that the root of ...

Preventing functionality with Jquery hashtag in the URL

My Jquery code successfully shows and hides divs with a button click, but it seems to only work for the first two clicks. After that, a hashtag appears in the URL and the script stops functioning. I attempted to add `e.preventDefault()` at the beginning ...

Using the AngularJS limitTo filter in ngRepeat for an object acting as a dictionary

Can the limitTo filter be used on a ngRepeat directive that is iterating over the properties of an Object instead of items in an Array? Although it is stated in the official documentation that the limitTo input should be an array or string, I am curious i ...

How can I transform an HTML div into a video file like MP4 using Python and Django?

I'm looking to take a HTML page and target a specific <div> within it in order to convert it into video format. Purpose: I understand that HTML is typically static, but I have a requirement to transform it into a video. I'm seeking method ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

What is the best way to parse a text file based on a specific delimiter and then store each element of the resulting array

I have been working on creating a login page, where I am trying to import the user's data into an array. The goal is to match the entered username and password with the ones stored in the array. Can someone please assist me with this? Text File: 72| ...

Using jQuery to apply a background image in CSS

Currently, I am attempting to utilize jQuery to set a background image for an HTML element. <div class="rmz-srchbg"> <input type="text" id="globalsearchstr" name="search" value="" class="rmz-txtbox"> <input type="submit" value="& ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Choose the number that is nearest to the options given in the list

I am faced with a challenge involving a list of numbers and an input form where users can enter any number, which I want to automatically convert to the closest number from my list. My list includes random numbers such as 1, 5, 10, 12, 19, 23, 100, 400, 9 ...

Encountering an error message stating that navigator.block is not a function when attempting to navigate to

Working on a React project, I have implemented a popup modal that should appear when a user tries to make changes in an input field and navigate to another screen. However, it is not functioning as expected. After researching various online resources, I ha ...

Java Modelmapper: Converter remains unused

I am currently developing a Java program that syncs Active Directory users with users in my database. To achieve this, I am utilizing modelmapper which is proving to be efficient and fast. However, I have added a converter to my mapping configuration. The ...

Having a hard time finding the perfect styling solution for Material UI

Is there a way for me to customize the styling of Material UI's components in addition to their default rules by injecting my own CSS? I'm unsure how I would go about setting these parameters using the styled-components API. Is this even doable? ...

The functionality of jQuery UI autocomplete is limited to only one use

My current setup involves using jQuery UI for an autocomplete field. However, after making changes to my PHP file to incorporate JSON encoding, I encountered an issue where the autocomplete functionality only works during the initial page load. Subsequentl ...

Creating a canvas texture on tube geometry with three.js for optimal display on iPad devices

I have a 3D model of a tube geometry with 18000 coordinates on the production side. To simplify, I am selecting every 9th coordinate to plot 9000 coordinates for building the tube geometry using only the CanvasRenderer. When utilizing vertexColors: THREE. ...

Selecting a database design pattern for varying database types

After creating a class to manage interactions with my database, I realized that I need separate classes for two different modes: admin and client. class MyDatabase { connect() { /* ... */ } } So, I decided to create two new classes: class MyDatabaseAd ...

React JS Task Manager | Extract input value and update state

I am currently working on developing a to do list application that by default receives two objects from a store. However, I am facing difficulty in capturing the user's input for their new "to do" item and storing it in the application state. When I ...

What sets the HTML5 cross-browser compatibility saga apart from that of CSS/JS?

Back when CSS and JS became popular, the major issue was that each browser interpreted them differently leading to limited functionality across different browsers. Now as HTML5 gains traction, it seems like we might be headed towards a similar situation, b ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...

Is it possible to retrieve every instance of a String and transform them into a List of Integer positions using Groovy?

When working with Strings in Groovy, it's convenient to use methods like String.findAll(String, Closure) This method finds all instances of a regular expression within a given String. Each match is then processed by the specified closure. The closu ...

What is the best approach for universally altering a color within a react component for optimal efficiency?

Is there a more efficient method to change the color of the contents in this TableCell react component globally to green? class TableCell extends Component { render() { return ( <SU_Table.Cell {...newProps}> {this.props.c ...