몽고DB findOne 예제
MongoDB findOne() 메서드는 입력한 기준을 만족하는 하나의 문서만 반환합니다. 입력한 기준이 둘 이상의 문서와 일치하는 경우 메서드는 문서가 데이터베이스에 저장된 순서를 반영하는 자연 순서에 따라 하나의 문서만 반환합니다.
몽고DB findOne
- projection 매개변수는 1 또는 true, 0 또는 false의 부울 값을 허용합니다. 프로젝션 필드를 지정하지 않으면 모든 필드가 검색됩니다.
- MongoDB findOne()은 제외되지 않는 한 프로젝션 매개변수에 명시적으로 지정되지 않은 경우에도 항상 _id 필드를 포함합니다.
- MongoDB findOne()은 문서만 반환하고 커서는 반환하지 않습니다.
MongoDB findOne - 빈 쿼리 사양
이 작업은 지정된 컬렉션에서 단일 문서를 반환합니다. 예: db.car.findOne()
출력:
{
"_id" : 2,
"name" : "Polo", "color" : "White",
"cno" : "H411", "speed" : 45, "mfdcountry" : "Japan"
}
car
컬렉션에서 하나의 레코드만 검색됩니다. "Polo\가 데이터베이스에 먼저 삽입되었음을 유의하십시오.
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, 이름 및 색상 필드가 있는 Car 컬렉션의 첫 번째 문서가 표시됩니다.
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"
이것은 자동차 "Polo\의 이름만 검색합니다.
MongoDB findOne 자바 예제
아래는 MongoDB findOne()과 함께 사용할 수 있는 다양한 옵션을 보여주는 Java 프로그램입니다. MongoDBFindOne.java
package com.journaldev.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 옵션을 살펴볼 것입니다. 참조: 공식 문서