MongoDBのfindOneの例は次のとおりです。

MongoDBのfindOne()メソッドは、入力した条件に一致するドキュメントを1つだけ返します。もし入力した条件が複数のドキュメントと一致する場合、メソッドはデータベースに格納されている順序を反映した自然な順序に従って1つのドキュメントのみを返します。

MongoDBのfindOne

MongoDBのfindOne()の構文は以下のようになります: db.collection.findOne(, ) criteria – 入力された選択条件を指定します。projection – 返されるドキュメントに表示されるフィールドのリストを指定します。MongoDBのfindOneについてのいくつかの重要なポイントは以下の通りです。

    1. 射影パラメーターは、1またはtrue、0またはfalseのブール値を受け付けます。射影フィールドが指定されていない場合、すべてのフィールドが取得されます。

 

    1. MongoDBのfindOne()は、_idフィールドを射影パラメーターで明示的に指定しない限り、常に含まれます。

 

    MongoDBのfindOne()は、ドキュメントのみを返すため、カーソルは返しません。

MongoDB の findOne – クエリ指定が空

指定されたコレクションから、1つのドキュメントを返します。例えば、db.car.findOne()の出力:

{
"_id" : 2,
"name" : "Polo", "color" : "White",
"cno" : "H411", "speed" : 45, "mfdcountry" : "Japan"
}

車のコレクションからレコードは1件だけ取得されます。データベースには最初に「ポロ」が挿入されたことに注意してください。

MongoDBのfindOne – クエリ仕様

指定されたコレクションから最初に一致するドキュメントを返すMongoDBのfindOne操作は、入力された選択基準とともに返されます。例えば、

>db.car.findOne(
... {
... $or:[
... {name:"Zen"},
... {speed: {$gt:60}} ... ]
... }
... )

{
"_id" : ObjectId("546cb92393f464ed49d620db"), 
"name" : "Zen",
"color" : "JetRed",
"cno" : "H671",
"speed" : 67, 
"mfdcountry" : "Rome"
}

「Zen」という名前の車か、または速度が60以上の車を検索し、条件を満たす最初のドキュメントを車のコレクションから取得する、この操作を実行します。

MongoDBのfindOne()でのプロジェクション

プロジェクションパラメータは、MongoDBのfindOneメソッドにも適用することができます。findOneにおいてプロジェクションを使用できるシナリオを見てみましょう。

MongoDBのfindOneメソッドを使用して、返されるフィールドを指定する。

この操作は、クエリで指定されたフィールドのみを表示します。例えば:

>db.car.findOne(
... { },
... {name:1,color:1}
... )

{ "_id" : 2, "name" : "Polo", "color" : "White" }

ID、名前、色のフィールドを持つカーコレクションの最初のドキュメントが表示されます。

MongoDBのfindOneメソッドは、除外されたフィールドを含めずにすべてのフィールドを返します。

選択基準に指定されたフィールドを除外した最初のドキュメントを取得するこの操作。例えば;

>db.car.findOne(
... { name:"Volkswagen" },
... {_id:0, mfdcountry:0,cno:0 }
... )

{ "name" : "Volkswagen", "color" : "JetBlue", "speed" : 62 }

Volkswagenという車の名称を取得しますが、id、mfdcountry、cnoのフィールドは除外されます。

MongoDBのfindOneの結果のドキュメント

この操作では、カーソルのメソッドは機能しません。なぜならそのメソッドは単一のドキュメントしか返さないからです。ドキュメントから各フィールドの値を印刷するためには、以下のコードを使用することができます。

>var car = db.car.findOne(); 
> if (car) {
...  var carName = car.name;
...  print (tojson(carName));
... }

"Polo"

この操作は、車の「ポロ」という名前のみを取得します。

ネイティブな日本語で以下を言い換えてください。オプションは1つだけ必要です。

JavaのMongoDBのfindOneの例

以下は、MongoDBのfindOne()メソッドを使用するためのさまざまなオプションを示すJavaプログラムです。MongoDBFindOne.java

package com.scdev.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

import java.net.UnknownHostException;

public class MongoDBFindOne {

	// method retrieves the first document without any criteria
	public static void emptyFindOne() throws UnknownHostException {

		// Get a new connection to the db assuming that it is running
		MongoClient mongoClient = new MongoClient("localhost");

		// use test as a datbase,use your database here
		DB db = mongoClient.getDB("test");

		// fetch the collection object ,car is used here,use your own
		DBCollection coll = db.getCollection("car");

		// invoking findOne() method
		DBObject doc = coll.findOne();

		// prints the resultant document
		System.out.println(doc);
	}

	// method that retrieves the document based on the selection criteria
	public static void querySpecification() throws UnknownHostException {
		// getting a connection everytime is not needed (could be done once
		// globally).
		MongoClient mongoClient = new MongoClient("localhost");
		DB db = mongoClient.getDB("test");
		DBCollection coll = db.getCollection("car");

		// query to filter the document based on name and speed values by
		// creating new object
		DBObject query = new BasicDBObject("name", "Zen").append("speed",
				new BasicDBObject("$gt", 30));

		// resultant document fetched by satisfying the criteria
		DBObject d1 = coll.findOne(query);

		// prints the document on console
		System.out.println(d1);
	}

	public static void projectionFields() throws UnknownHostException {

		MongoClient mongoClient = new MongoClient("localhost");
		DB db = mongoClient.getDB("test");
		DBCollection coll = db.getCollection("car");

		// creates new db object
		BasicDBObject b1 = new BasicDBObject();

		// criteria to display only name and color fields in the resultant
		// document
		BasicDBObject fields = new BasicDBObject("name", 1).append("color", 1);

		// method that retrieves the documents by accepting fields and object
		// criteria
		DBObject d1 = coll.findOne(b1, fields);

		System.out.println(d1);

	}

	public static void excludeByfields() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");

		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// filter criteria for car name volkswagen
		DBObject query = new BasicDBObject("name", "Volkswagen");

		// excluding the fields mfdcountry,cno and id fields
		BasicDBObject fields = new BasicDBObject("mfdcountry", 0).append("cno",
				0).append("_id", 0);

		DBObject d1 = col.findOne(query, fields);
		System.out.println(d1);
	}

	public static void printDoc() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		
		DBObject d1 = col.findOne();
		
		// prints only the name of the car
		System.out.println((d1.get("name")));
	}
	
	public static void main(String[] args) throws UnknownHostException {
		// invoking all the methods from main
		emptyFindOne();
		querySpecification();
		projectionFields();
		excludeByfields();
		printDoc();
	}

}

上記のプログラムの出力は次の通りです。

{ "_id" : 2.0 , "name" : "Polo" , "color" : "White" , "cno" : "H411" , "speed" : 45.0 , "mfdcountry" : "Japan"} ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
{ "_id" : { "$oid" : "546cb92393f464ed49d620db"} , "name" : "Zen" , "color" : "JetRed" , "cno" : "H671" , "speed" : 67 , "mfdcountry" : "Rome"}
{ "_id" : 2.0 , "name" : "Polo" , "color" : "White"}
{ "name" : "Volkswagen" , "color" : "JetBlue" , "speed" : 62}
Polo

MongoDBのfindOne()メソッドについては以上です。今後の記事で他のMongoDBのオプションも見ていきます。参考:公式ドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *