MongoDB에서 결과로 특정 필드를 얻으려면 findOne()을 사용할 수 있습니다. 다음은 구문입니다 -
db.yourCollectionName.findOne({"yourFieldName1":yourValue},{yourFieldName2:1});
먼저 문서로 컬렉션을 생성해 보겠습니다. −
> db.particularFieldDemo.insertOne({"EmployeeName":"John Smith","EmployeeAge":26,"EmployeeTechnology":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4abb50a6c6dd317ada2") } > db.particularFieldDemo.insertOne({"EmployeeName":"Chris Brown","EmployeeAge":28,"EmployeeTechnology":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4d2b50a6c6dd317ada3") } > db.particularFieldDemo.insertOne({"EmployeeName":"David Miller","EmployeeAge":30,"EmployeeTechnology":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4e8b50a6c6dd317ada4") } > db.particularFieldDemo.insertOne({"EmployeeName":"John Doe","EmployeeAge":31,"EmployeeTechnology":"C++"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b527b50a6c6dd317ada5") }
다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다. -
> db.particularFieldDemo.find().pretty();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5cd9b4abb50a6c6dd317ada2"), "EmployeeName" : "John Smith", "EmployeeAge" : 26, "EmployeeTechnology" : "MongoDB" } { "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"), "EmployeeName" : "Chris Brown", "EmployeeAge" : 28, "EmployeeTechnology" : "Java" } { "_id" : ObjectId("5cd9b4e8b50a6c6dd317ada4"), "EmployeeName" : "David Miller", "EmployeeAge" : 30, "EmployeeTechnology" : "MySQL" } { "_id" : ObjectId("5cd9b527b50a6c6dd317ada5"), "EmployeeName" : "John Doe", "EmployeeAge" : 31, "EmployeeTechnology" : "C++" }
다음은 MongoDB에서 결과로 특정 필드를 찾는 쿼리입니다 -
> db.particularFieldDemo.findOne({"EmployeeTechnology":"Java"},{EmployeeName:1});
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"), "EmployeeName" : "Chris Brown" }