Oc-windows.ru

IT Новости из мира ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Mongodb java example

MongoDB Java tutorial

In this tutorial, we show how to work with MongoDB in Java. There is a concise Java tutorial on ZetCode.

is a NoSQL cross-platform document-oriented database. It is one of the most popular databases available. MongoDB is developed by MongoDB Inc. and is published as free and open-source software.

A in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections. are analogous to tables in relational databases and documents to rows.

MongoDB represents JSON documents in binary-encoded format called BSON behind the scenes. BSON extends the JSON model to provide additional data types, ordered fields, and to be efficient for encoding and decoding within different languages. The .NET driver uses BsonDocument to represent BSON .

Installing MongoDB

The following command can be used to install MongoDB on a Debian-based Linux.

The command installs the necessary packages that come with MongoDB.

With the sudo service mongodb status command we check the status of the mongodb server.

The mongodb server is started with the sudo service mongodb start command.

Creating a database

The mongo tool is an interactive JavaScript shell interface to MongoDB, which provides an interface for systems administrators as well as a way for developers to test queries and operations directly with the database.

We create a testdb database and insert eight documents in the cars collection.

Java MongoDB driver

We use the following Maven declaration to include the MongoDB Java driver in our project.

It is an all-in-one JAR, which embeds the core driver and BSON. , short for BinВ­ary JSON, is a binВ­ary-enВ­coded seriВ­alВ­izВ­aВ­tion of JSON-like docВ­uВ­ments.

Java MongoDB list database collections

The first example connects to the testdb database and retrieves its collections.

This is our pom.xml file.

The example connects to the testdb database and retrieves all its collections.

We set the logging level for MongoDB. We only show SEVERE error messages.

A MongoClient class is used to connect to the MongoDB server. It is created with the MongoClients.create() method call. The 27017 is the default port on which the MongoDB server listens.

With the getDatabase() method, we retrieve the testdb database.

The listCollectionNames() method finds all the collections in the testdb database.

In our database, we have these two collections.

Java MongoDB database statistics

The next example connects to the testdb database and gets its statistics.

The example connects to the testdb database and executes the dbstats command. It shows some database statistics.

With the runCommand() method, we execute the dbstats command. The command returns a Document , which is a representation of a MongoDB document as a map.

We iterate through the entries of the document.

This is a sample output.

Java MongoDB read data

MongoCollection is used to store mongo documents returned from a collection. MongoCursor is a cursor to iterate through the results of a database query. It makes sure that it is closed in case of an exception.

In the example, we iterate over all data of the cars collection.

We retrieve the cars collection with the getCollection() method.

We iterate through the documents of the collection. The find() method finds all documents in the collection.

This is the output of the example.

Java MongoDB query operators

It is possible to filter the data using MongoDB query operators such as $gt , $lt , or $ne . The query operators can be specified in the BasicDBObject class.

The example prints all documents whose car prices’ are greater than 30,000.

We use the $gt query operator.

The forEach() method is a syntactic sugar to avoid the need for the application code to worry about having to close the cursor manually. The data is printed in the JSON format using the toJson() method.

This is the output of the example in the JSON format. Only cars more expensive than 30,000 are included.

Java MongoDB factory filter query methods

The Java MongoDB driver contains factory methods for query filters.

In the example, we retrieve cars whose prices fall between 20,000 and 50,000.

The and() , gt() , and lt() are factory filter methods. In addition, the data is sorted with the sort() method.

This is the output of the example.

Java MongoDB projections

The Projections class provides static factory methods for all the MongoDB projection operators. By default, all fields of each document are projected. We can use the include and exclude() methods to determine which fields should be projected into our output.

The example excludes the _id field from the output.

The projection() method sets a document describing the fields to return for all matching documents. The excludeId() is a synonym for exclude(«_id») .

Читать еще:  Java sql sqlexception invalid column index

This is the output for the example.

Java MongoDB limit data output

The limit query option specifies the number of documents to be returned and the skip() option skips the specified number of documents.

The example reads from the testdb.cars collection, skips the first two documents, and limits the output to five documents.

The FindIterable’s skip() method skips the first two documents and the limit() method limits the output to five documents.

Here we use Java 8 construct to print the documents.

This is the output of the example.

Java MongoDB create collection

The MongoDatabase’s createCollection() method creates a new collection in the database. The MongoCollection’s insertMany() method inserts one or more documents into the collection.

The example creates a cars collection and inserts nine documents into it.

A new collection is created with the createCollection() method. If the collection already exists, it is dropped.

A MongoCollection of documents is created with the getCollection() method.

A new Document is created. It contains the information about the car—its ID, name, and price.

The documents are written to the collection with the insertMany() method.

Java MongoDB create collection from JSON

The JSON class has methods for parsing JSON documents. (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.

The example creates a continents collection from JSON data.

JSON data is parsed with the BasicDBObject.parse method.

The BasicDBObject is passed to Document and inserted into the collection with the insertOne() method.

We show the created collection with mongo .

Java MongoDB modify documents

The MongoCollection’s deleteOne() method is used to delete a document and updateOne() to update a document.

The example deletes a document containing Skoda and updates the price of Audi.

The deleteOne() deletes the document of Skoda . The eq() creates a filter that matches all documents where the value of the field name equals the specified value.

The price of Audi is changed to 52,000 with the updateOne() method.

We confirm the changes with the mongo tool.

In this tutorial, we have worked with MongoDB and Java. You might be also interested in Spring Boot MongoDB tutorial, MySQL Java tutorial, or PostgreSQL Java tutorial.

MongoDB Java CRUD Example Tutorial

Welcome to MongoDB Java Example Tutorial. Earlier we learned how to install MongoDB in Unix machines and executed some commands from terminal. Today we will look into the MongoDB Java Driver features and how to perform common CRUD (Create, Read, Update, Delete) operations.

MongoDB Java

MongoDB Java Driver Download

If you have maven project, just add below dependency to include MongoDB java driver into your application.

If you have a standalone project, you can download MongoDB Java Driver from this link and include it in your project build path.

Now let’s go through some basic usage of MongoDB java driver and then we will look into MongoDB Java Example program for CRUD operations.

Creating MongoDB Java Connection

MongoClient is the interface between our java program and MongoDB server. MongoClient is used to create connection, connect to database, retrieve collection names and create/read/update/delete database, collections, document etc.

One of the MongoDB java driver feature I like most is that it’s thread safe, so we can create an instance of MongoClient once and reuse it. Even if multiple thread accesses it simultaneously, a connection is returned from the internal connection pool maintained by it.

For every request to the database (find, insert etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

Below are some of the common methods to connect to a MongoDB server.

Connection to MongoDB Database

Once we get the connection to MongoDB server, next step is to create the connection to the database, as shown below. Note that if database is not present, MongoDB will create it for you.

MongoClient provide a useful method to get all the database names, as shown below.

We can have user-password based authentication for databases, in that case we need to provide authorization credentials like below.

If you are using older versions, you need to provide authentication details after getting the database object like below.

You can easily figure out flaws in the earlier approach, the authentication should be done at early stage because we can’t recover from it.

We can drop a database either by using MongoClient dropDatabase(String db) method or by DB dropDatabase() method. Since we are dropping the database, i prefer to use MongoClient method.

MongoDB and Collections

Every database can have zero or multiple collections, they are like tables in relational database servers except that you don’t have specific format of data. Think of it like a generic list vs list of Strings in terms of java programming language.

Читать еще:  Java security cert certpathvalidatorexception trust

We can get all the collections names using below code.

We can get a specific collection by providing it’s name, as shown below.

Again if the collection doesn’t exist, MongoDB will create it for you. All the data in MongoDB goes into some collection, so at this point we are ready to perform insert/update/delete operations.

We can use DBCollection drop() method to drop a collection from the database.

MongoDB Java Example

Even though we can work on any valid JSON document in MongoDB collection, in real life we have POJO classes that are mapped with these data. So I will create a java bean and use it for my examples.

Here is the complete MongoDB java example program showing all the CRUD operations one by one.

A sample execution results in following output.

Notice that I am saving User id with _id name, this is a reserved key for the primary key of any record in the collection. If we don’t provide one, MongoDB will create one for us. It’s like sequencer or auto increment column in relational database tables.

Since I am deleting the created record, further execution won’t cause any issues. But if there are duplicate record, then we will get below errors.

That’s all for getting your started with MongoDB Java Driver, we will look into more features in next posts.

A Gu >Last modified: March 5, 2020

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

In this article, we’ll have a look at integrating MongoDB, a very popular NoSQL open source database with a standalone Java client.

MongoDB is written in C++ and has quite a number of solid features such as map-reduce, auto-sharding, replication, high availability etc.

2. MongoDB

Let’s start with a few key points about MongoDB itself:

  • stores data in JSON-like documents that can have various structures
  • uses dynamic schemas, which means that we can create records without predefining anything
  • the structure of a record can be changed simply by adding new fields or deleting existing ones

The above-mentioned data model gives us the ability to represent hierarchical relationships, to store arrays and other more complex structures easily.

3. Terminologies

Understanding concepts in MongoDB becomes easier if we can compare them to relational database structures.

Let’s see the analogies between Mongo and a traditional MySQL system:

  • Table in MySQL becomes a Collection in Mongo
  • Row becomes a Document
  • Column becomes a Field
  • Joins are defined as linking and embedded documents

This is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.

Now, let’s dive into implementation to understand this powerful database.

4. Maven Dependencies

We need to start by defining the dependency of a Java Driver for MongoDB:

To check if any new version of the library has been released – track the releases here.

5. Using MongoDB

Now, let’s start implementing Mongo queries with Java. We will follow with the basic CRUD operations as they are the best to start with.

5.1. Make a Connection With MongoClient

First, let’s make a connection to a MongoDB server. With version >= 2.10.0, we’ll use the MongoClient:

And for older versions use Mongo class:

5.2. Connecting to a Database

Now, let’s connect to our database. It is interesting to note that we don’t need to create one. When Mongo sees that database doesn’t exist, it will create it for us:

Sometimes, by default, MongoDB runs in authenticated mode. In that case, we need to authenticate while connecting to a database.

We can do it as presented below:

5.3. Show Existing Databases

Let’s display all existing databases. When we want to use the command line, the syntax to show databases is similar to MySQL:

In Java, we display databases using snippet below:

The output will be:

Above, local is the default Mongo database.

5.4. Create a Collection

Let’s start by creating a Collection (table equivalent for MongoDB) for our database. Once we have connected to our database, we can make a Collection as:

Читать еще:  Java lang arrayindexoutofboundsexception 8

Now, let’s display all existing collections for current database:

The output will be:

5.5. Save – Insert

The save operation has save-or-update semantics: if an id is present, it performs an update, if not – it does an insert.

When we save a new customer:

The entity will be inserted into a database:

Next, we’ll look at the same operation – save – with update semantics.

5.6. Save – Update

Let’s now look at save with update semantics, operating on an existing customer:

Now, when we save the existing customer – we will update it:

The database will look like this:

As you can see, in this particular example, save uses the semantics of update, because we use object with given _id.

5.7. Read a Document From a Collection

Let’s search for a Document in a Collection by making a query:

It will show the only Document we have by now in our Collection:

5.8. Delete a Document

Let’s move forward to our last CRUD operation, deletion:

With above command executed, our only Document will be removed from the Collection.

6. Conclusion

This article was a quick introduction to using MongoDB from Java.

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven based project, so it should be easy to import and run as it is.

Mongodb java example

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

mongodb-driver-examples / java / JavaSimpleExample.java

Users who have contributed to this file

/*
* Copyright (c) 2017 ObjectLabs Corporation
* Distributed under the MIT license — http://opensource.org/licenses/MIT
*
* Written with mongo-3.4.2.jar
* Documentation: http://api.mongodb.org/java/
* A Java class connecting to a MongoDB database given a MongoDB Connection URI.
*/
import java.net.UnknownHostException ;
import com.mongodb.MongoClient ;
import com.mongodb.MongoClientURI ;
import com.mongodb.ServerAddress ;
import com.mongodb.client.MongoDatabase ;
import com.mongodb.client.MongoCollection ;
import org.bson.Document ;
import java.util.Arrays ;
import com.mongodb.Block ;
import com.mongodb.client.MongoCursor ;
import static com.mongodb.client.model.Filters.* ;
import com.mongodb.client.result.DeleteResult ;
import static com.mongodb.client.model.Updates.* ;
import com.mongodb.client.result.UpdateResult ;
import java.util.ArrayList ;
import java.util.List ;
public class JavaSimpleExample <
public static void main ( String [] args ) throws UnknownHostException <
// Create seed data
List Document > seedData = new ArrayList Document > ();
seedData . add( new Document ( » decade » , » 1970s » )
.append( » artist » , » Debby Boone » )
.append( » song » , » You Light Up My Life » )
.append( » weeksAtOne » , 10 )
);
seedData . add( new Document ( » decade » , » 1980s » )
.append( » artist » , » Olivia Newton-John » )
.append( » song » , » Physical » )
.append( » weeksAtOne » , 10 )
);
seedData . add( new Document ( » decade » , » 1990s » )
.append( » artist » , » Mariah Carey » )
.append( » song » , » One Sweet Day » )
.append( » weeksAtOne » , 16 )
);
// Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
MongoClientURI uri = new MongoClientURI ( » mongodb://user:pass@host:port/db » );
MongoClient client = new MongoClient (uri);
MongoDatabase db = client . getDatabase(uri . getDatabase());
/*
* First we’ll add a few songs. Nothing is required to create the
* songs collection; it is created automatically when we insert.
*/
MongoCollection Document > songs = db . getCollection( » songs » );
// Note that the insert method can take either an array or a document.
songs . insertMany(seedData);
/*
* Then we need to give Boyz II Men credit for their contribution to
* the hit «One Sweet Day».
*/
Document updateQuery = new Document ( » song » , » One Sweet Day » );
songs . updateOne(updateQuery, new Document ( » $set » , new Document ( » artist » , » Mariah Carey ft. Boyz II Men » )));
/*
* Finally we run a query which returns all the hits that spent 10
* or more weeks at number 1.
*/
Document findQuery = new Document ( » weeksAtOne » , new Document ( » $gte » , 10 ));
Document orderBy = new Document ( » decade » , 1 );
MongoCursor Document > cursor = songs . find(findQuery) . sort(orderBy) . iterator();
try <
while (cursor . hasNext()) <
Document doc = cursor . next();
System . out . println(
» In the » + doc . get( » decade » ) + » , » + doc . get( » song » ) +
» by » + doc . get( » artist » ) + » topped the charts for » +
doc . get( » weeksAtOne » ) + » straight weeks. «
);
>
> finally <
cursor . close();
>
// Since this is an example, we’ll clean up after ourselves.
songs . drop();
// Only close the connection when your app is terminating
client . close();
>
>
  • © 2020 GitHub, Inc.
  • Terms
  • Privacy
  • Security
  • Status
  • Help

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Ссылка на основную публикацию
Adblock
detector