Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB 문서에서 이메일 ID를 가져와 print()로 출력하는 방법

MongoDB에서 저장된 문서의 특정 필드 값만 추출하여 확인하고 싶을 때가 있습니다. 이 글에서는 forEach() 메서드와 print() 함수를 함께 사용하여 MongoDB 문서에서 이메일 ID(UserEmailId) 값을 가져와 출력하는 방법을 단계별로 알아봅니다.

1. 샘플 컬렉션 생성하기

먼저 insertOne() 메서드를 사용하여 문서가 포함된 컬렉션을 생성합니다.

> db.demo690.insertOne({"UserName":"John","UserEmailId":"John@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db31551299a9f98c939c")
}
> db.demo690.insertOne({"UserName":"Bob","UserEmailId":"Bob@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db3c551299a9f98c939d")
}
> db.demo690.insertOne({"UserName":"David","UserEmailId":"David@gmail.com"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6db47551299a9f98c939e")
}

위 코드는 demo690이라는 컬렉션에 John, Bob, David 세 명의 사용자 문서를 각각 삽입합니다.

2. find()로 전체 문서 조회하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 한눈에 확인할 수 있습니다.

> db.demo690.find();

이 명령은 다음과 같은 결과를 출력합니다.

{ "_id" : ObjectId("5ea6db31551299a9f98c939c"), "UserName" : "John", "UserEmailId" : "John@gmail.com" }
{ "_id" : ObjectId("5ea6db3c551299a9f98c939d"), "UserName" : "Bob", "UserEmailId" : "Bob@gmail.com" }
{ "_id" : ObjectId("5ea6db47551299a9f98c939e"), "UserName" : "David", "UserEmailId" : "David@gmail.com" }

3. forEach()와 print()로 이메일 ID만 출력하기

다음은 MongoDB 문서에서 이메일 ID를 가져와 print() 함수로 출력하는 쿼리입니다.

> db.demo690.find().forEach(function(document) {
...    print(document.UserEmailId);
... });

실행 결과는 다음과 같습니다.

John@gmail.com
Bob@gmail.com
David@gmail.com

이처럼 find()로 얻은 커서에 forEach()를 적용하면 각 문서를 순회하면서 원하는 필드 값만 손쉽게 추출할 수 있습니다. 전체 문서가 아닌 특정 필드만 반복적으로 확인해야 하는 경우 매우 유용하게 활용되는 패턴이므로 꼭 기억해 두시기 바랍니다.