Mongodb-java

提供:Dev Guides
移動先:案内検索

MongoDB-Java

この章では、MongoDB JDBCドライバーをセットアップする方法を学びます。

インストール

JavaプログラムでMongoDBの使用を開始する前に、MongoDB JDBCドライバーとJavaがマシンにセットアップされていることを確認する必要があります。 マシンにJavaをインストールするためのJavaチュートリアルを確認できます。 次に、MongoDB JDBCドライバーのセットアップ方法を確認しましょう。

 *jar* mongodb-driver-3.11.2.jarとその依存関係mongodb-driver-core-3.11.2.jar。*をダウンロードする必要があります。 これらのjarファイルの最新リリースをダウンロードしてください。
* ダウンロードしたjarファイルをクラスパスに含める必要があります。

データベースに接続する

データベースに接続するには、データベース名を指定する必要があります。データベースが存在しない場合は、MongoDBが自動的に作成します。

以下は、データベースに接続するためのコードスニペットです-

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ConnectToDB {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );

     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");
      System.out.println("Credentials ::"+ credential);
   }
}

次に、上記のプログラムをコンパイルして実行し、以下に示すようにデータベースmyDbを作成します。

$javac ConnectToDB.java
$java ConnectToDB

実行すると、上記のプログラムは次の出力を提供します。

Connected to the database successfully
Credentials ::MongoCredential{
   mechanism = null,
   userName = 'sampleUser',
   source = 'myDb',
   password = <hidden>,
   mechanismProperties = {}
}

コレクションを作成する

コレクションを作成するには、 com.mongodb.client.MongoDatabase クラスの* createCollection()*メソッドを使用します。

以下は、コレクションを作成するためのコードスニペットです-

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );

     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");

     //Creating a collection
      database.createCollection("sampleCollection");
      System.out.println("Collection created successfully");
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection created successfully

コレクションの取得/選択

データベースからコレクションを取得/選択するには、 com.mongodb.client.MongoDatabase クラスの* getCollection()*メソッドを使用します。

以下は、コレクションを取得/選択するプログラムです-

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class selectingCollection {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );

     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");

     //Creating a collection
      System.out.println("Collection created successfully");
     //Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("myCollection");
      System.out.println("Collection myCollection selected successfully");
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection created successfully
Collection myCollection selected successfully

ドキュメントを挿入する

MongoDBにドキュメントを挿入するには、 com.mongodb.client.MongoCollection クラスの* insert()*メソッドが使用されます。

以下は、ドキュメントを挿入するためのコードスニペットです-

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
    public static void main( String args[] ) {

   //Creating a Mongo client
    MongoClient mongo = new MongoClient( "localhost" , 27017 );

   //Accessing the database
    MongoDatabase database = mongo.getDatabase("myDb");

   //Creating a collection
    database.createCollection("sampleCollection");
    System.out.println("Collection created successfully");

   //Retrieving a collection
    MongoCollection<Document> collection = database.getCollection("sampleCollection");
    System.out.println("Collection sampleCollection selected successfully");
    Document document = new Document("title", "MongoDB")
    .append("description", "database")
    .append("likes", 100)
    .append("url", "http://www.finddevguides.com/mongodb/")
    .append("by", "tutorials point");

   //Inserting document into the collection
    collection.insertOne(document);
    System.out.println("Document inserted successfully");
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection sampleCollection selected successfully
Document inserted successfully

すべてのドキュメントを取得

コレクションからすべてのドキュメントを選択するには、 com.mongodb.client.MongoCollection クラスの* find()*メソッドが使用されます。 このメソッドはカーソルを返すため、このカーソルを繰り返す必要があります。

以下は、すべてのドキュメントを選択するプログラムです-

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments {
    public static void main( String args[] ) {

       //Creating a Mongo client
        MongoClient mongo = new MongoClient( "localhost" , 27017 );

       //Creating Credentials
        MongoCredential credential;
        credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray());
        System.out.println("Connected to the database successfully");

       //Accessing the database
        MongoDatabase database = mongo.getDatabase("myDb");

       //Retrieving a collection
        MongoCollection<Document> collection = database.getCollection("sampleCollection");
        System.out.println("Collection sampleCollection selected successfully");
        Document document1 = new Document("title", "MongoDB")
        .append("description", "database")
        .append("likes", 100)
        .append("url", "http://www.finddevguides.com/mongodb/")
        .append("by", "tutorials point");
        Document document2 = new Document("title", "RethinkDB")
        .append("description", "database")
        .append("likes", 200)
        .append("url", "http://www.finddevguides.com/rethinkdb/")
        .append("by", "tutorials point");
        List<Document> list = new ArrayList<Document>();
        list.add(document1);
        list.add(document2);
        collection.insertMany(list);
       //Getting the iterable object
        FindIterable<Document> iterDoc = collection.find();
        int i = 1;
       //Getting the iterator
        Iterator it = iterDoc.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
            i++;
        }
    }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection sampleCollection selected successfully
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.finddevguides.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.finddevguides.com/rethinkdb/, by=tutorials point}}

ドキュメントを更新

コレクションからドキュメントを更新するには、 com.mongodb.client.MongoCollection クラスの* updateOne()*メソッドが使用されます。

以下は、最初のドキュメントを選択するプログラムです-

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class UpdatingDocuments {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );

     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");
     //Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection myCollection selected successfully");
      collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));
      System.out.println("Document update successfully...");

     //Retrieving the documents after updation
     //Getting the iterable object
      FindIterable<Document> iterDoc = collection.find();
      int i = 1;
     //Getting the iterator
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
         i++;
      }
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection myCollection selected successfully
Document update successfully...
Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.finddevguides.com/mongodb/, by=tutorials point}}
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.finddevguides.com/rethinkdb/, by=tutorials point}}

ドキュメントを削除する

コレクションからドキュメントを削除するには、 com.mongodb.client.MongoCollection クラスの* deleteOne()*メソッドを使用する必要があります。

以下は、ドキュメントを削除するプログラムです-

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DeletingDocuments {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );

     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");
     //Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
      System.out.println("Collection sampleCollection selected successfully");
     //Deleting the documents
      collection.deleteOne(Filters.eq("title", "MongoDB"));
      System.out.println("Document deleted successfully...");

     //Retrieving the documents after updation
     //Getting the iterable object
      FindIterable<Document> iterDoc = collection.find();
      int i = 1;
     //Getting the iterator
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
         i++;
      }
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection sampleCollection selected successfully
Document deleted successfully...
Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.finddevguides.com/rethinkdb/, by=tutorials point}}

コレクションの削除

データベースからコレクションを削除するには、 com.mongodb.client.MongoCollection クラスの* drop()*メソッドを使用する必要があります。

以下は、コレクションを削除するプログラムです-

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DropingCollection {

   public static void main( String args[] ) {
     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");

     //Creating a collection
      System.out.println("Collections created successfully");
     //Retrieving a collection
      MongoCollection<Document> collection = database.getCollection("sampleCollection");
     //Dropping a Collection
      collection.drop();
      System.out.println("Collection dropped successfully");
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection sampleCollection selected successfully
Collection dropped successfully

すべてのコレクションのリスト

データベース内のすべてのコレクションをリストするには、 com.mongodb.client.MongoDatabase クラスの* listCollectionNames()*メソッドを使用する必要があります。

以下は、データベースのすべてのコレクションを一覧表示するプログラムです-

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ListOfCollection {

   public static void main( String args[] ) {

     //Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
     //Creating Credentials
      MongoCredential credential;
      credential = MongoCredential.createCredential("sampleUser", "myDb",
         "password".toCharArray());
      System.out.println("Connected to the database successfully");

     //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDb");
      System.out.println("Collection created successfully");
      for (String name : database.listCollectionNames()) {
         System.out.println(name);
      }
   }
}

コンパイルすると、上記のプログラムはあなたに次の結果を与えます-

Connected to the database successfully
Collection created successfully
myCollection
myCollection1
myCollection5

残りのMongoDBメソッド* save()、limit()、skip()、sort()*など 後続のチュートリアルで説明したのと同じように機能します。