🌿

5. CRUD-읽기(Read)

 
 

1. find

이번에는 컬렉션에 문서를 검색하는 방법에 대해 알아보겠습니다.
  • findOne : 조건에 맞는 하나의 문서를 검색합니다.
  • find : 조건에 맞는 하나 또는 여러가지 문서를 검색합니다.
 
모든 문서의 내용을 검색해 보도록 하겠습니다. 조건을 생략하는 경우나 중괄호{} 인 경우에는 빈문서를 전달하는 것과 같습니다.
db.user_info.find() db.user_info.find({})
notion imagenotion image
 
문서를 보기 쉽게 읽을 수 있습니다.
db.user_info.find().pretty()
notion imagenotion image
 
출력을 json형식으로 출력할 수도 있습니다.
db.user_info.find().forEach(printjson)
notion imagenotion image
 
조건을 지정해 여러가지 문서를 검색할 때에는 find에 전달합니다.
db.user_info.find( { ABO: "B" } )
notion imagenotion image
 
조건에 맞는 하나의 문서를 검색할 때에는 findOne을 사용합니다.
db.user_info.findOne({"gender":"F"})
notion imagenotion image
 

2. 프로젝션(projection)

프로젝션은 문서에서 반환할 필드를 선택하는 것을 말합니다. 조건에 맞는 원하는 필드만 검색하고 싶을 때에는 1을 입력합니다. 이때, _id는 기본적으로 반환됩니다.
db.user_info.find({"gender":"F"}, {"name":1})
notion imagenotion image
 
_id 필드를 숨기고 싶으신 경우에는 0을 입력합니다.
db.user_info.find({},{_id:0, "name":1}) db.user_info.find({},{_id:0, "name":1, "gender":1}) // 뒤에서 합니다.
notion imagenotion image
 
일부 필드를 0으로 설정하고 다른 필드를 1로 설정할 때 오류가 발생합니다. 포함과 제외를 함께 사용할 수 없으며, 예외로 id 필드를 혼합한 경우는 오류를 발생하지 않습니다.
db.user_info.find({},{_id:0,"name":0,"age":1})
notion imagenotion image
 
_id를 숨긴 후 여러가지 필드를 출력할 수 있습니다.
db.user_info.find({},{_id:0,"name":1,"age":1})
notion imagenotion image
 
특정 필드를 숨길 수도 있습니다.
db.user_info.find({},{"name":0,"age":0})
notion imagenotion image
 
포함된 문서의 필드 또는 배열를 반환할 때에는 점 표기법을 이용합니다.
db.user_info.find({},{"gender":1,"size.h":1})
notion imagenotion image
 
또한 중첩으로 필드를 지정할 수 있습니다.
db.user_info.find({},{"gender":1,"size":{"h":1}})
notion imagenotion image
 
$slice를 이용해 배열 데이터에서 몇 개를 받아올지 정할 수 있습니다.
db.user_info.find({},{"gender":1,"coupon":{"$slice":1}})
notion imagenotion image
 
findOne을 사용하면 하나의 값만 찾습니다. 주로 고유의 값을 찾을 때 사용합니다.
db.user_info.findOne({userid : 'licat'})