• 회원가입
  • 로그인
  • 구글아이디로 로그인

[mongodb] Python - MongoDB Find (데이터 찾기)

11689  

목차

  1. find_one() 메서드 - collection에서 1개 데이터 찾기
  2. find() 메서드 - collection에서 여러 데이터 가져오기
  3. 일부 컬럼의 데이터만 가져오기
  4. 일부 컬럼 제외 시, 에러 발생 경우

 

MongoDB :  find(), find_one() 메서드로 컬렉션에서 데이터 찾음.
cf. MySQL : SELECT 문 사용해, 테이블에서 데이터를 찾음 .
 

find_one() 메서드 - collection에서 1개 데이터 찾기

find_one() 메서드 이용.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

x = mycol.find_one()

print(x)


결과값: {'_id': 1, 'mb_name': 'AAA', 'mb_level': '1'}

 

find() 메서드 - collection에서 여러 데이터 가져오기

find() 메서드 이용.


1.  

선택 항목의 모든 항목을 반환.

 

2.

find()메서드의 첫 번째 매개변수 는 쿼리 객체임. 

이 예에서는 컬렉션의 모든 문서를 선택하는 빈 쿼리 개체를 사용.

 

3.

find() 메서드에 매개변수 없으면 MySQL의 SELECT * 와 동일한 결과 제공.

 


[예제]

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find():

  print(x)

 

결과값:

{'_id': 1, 'mb_name': 'AAA', 'mb_level': '1'}

{'_id': 2, 'mb_name': 'BBB', 'mb_level': '2'}

...

 

일부 컬럼의 데이터만 가져오기

 

1.

find() 메서드의 두 번째 매개변수는 컬럼 출력 여부 결정 객체임.

※ 값이 0인 컬럼 경우 : 출력 X

※ 값이 1인 컬럼 경우 : 출력 O

 

2.

이 매개 변수는 선택 사항이며, 생략 시 모든 필드가 결과에 포함.

 

3.

동일 객체에서 0과 1 값을 모두 지정 시 에러 발생. 
(단, 필드 중 하나가 _id 필드 인 경우엔 괜찮음.)
 
4. 
값이 0인 필드 명시한 경우, 다른 모든 필드는 묵시적으로 1 가짐.
※ 그 반대 경우도 마찬가지.

 


[정상 예제1] _id 컬럼 출력 제외.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "_id": 0, "mb_name": 1, "mb_level": 1 }):

  print(x) 

 

결과값:

{'mb_name': 'AAA', 'mb_level': '1'}

{'mb_name': 'BBB', 'mb_level': '2'}

...


[정상 예제2] mb_level 컬럼 출력 제외.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "mb_level": 0 }):

  print(x)

 

결과값:

{'_id': 1, 'mb_name': 'AAA'}

{'_id': 2, 'mb_name': 'BBB'}

...

 


[정상 예제3] _id와 mb_level 컬럼 출력 제외

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, {"_id": 0,  "mb_level": 0 }):

  print(x)

 

결과값:

{'mb_name': 'AAA'}

{'mb_name': 'BBB'}

... 


[정상 예제4] _id 컬럼 출력 제외.

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, {"_id": 0}):

  print(x)

 

결과값:

{'mb_name': 'AAA', 'mb_level': '1'}

{'mb_name': 'BBB', 'mb_level': '2'}

...

 

 

일부 컬럼 제외 시, 에러 발생 경우

 

동일한 객체에 0과 1 모두 지정하면 오류 발생.
단, 필드 중 하나가 _id 필드 인 경우엔 무방함.
 

 


[에러 예제1] _id 속성 아닌 다른 컬럼에 0과 1 지정.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "mb_name": 1, "mb_level": 0 }):

  print(x)

 

결과값: 에러 발생.


[에러 예제2] _id 속성 아닌 다른 컬럼에 0과 1 지정.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "mb_name": 0, "mb_level": 1 }):

  print(x)

 

결과값: 에러 발생.


[에러 예제3] _id 속성 아닌 다른 컬럼에 0과 1 지정.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "_id": 0, "mb_name": 0, "mb_level": 1 }):

  print(x) 

 

결과값: 에러 발생


[에러 예제4] _id 속성 아닌 다른 컬럼에 0과 1 지정.

 

import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')

mydb = myclient['hz']

mycol = mydb["hz_member"]

for x in mycol.find({}, { "_id": 0, "mb_name": 1, "mb_level": 0 }):

  print(x)

 

결과값: 에러 발생.



분류 제목
mongodb Python - MongoDB Limit (데이터 출력개수)
module Python - random 모듈 메서드 종류
module Python - random.seed() 메서드 - 난수 생성기 초기화 (= seed메서드 = 시드)
module Python - random.getstate() 메서드 - 난수 생성기 현재 상태 반환. (= getstat…
module Python - random.setstate() 메서드 - 난수 생성기 상태 복원. (= setstate메서…
module Python - random.getrandbits() 메서드 ★ - 지정 bit 크기의 정수 반환. (= g…
module Python - random.randrange() 메서드 ★★ - 지정 범위 안에서 정수형 난수 반환. (=…
module Python - random.randint() 메서드 ★★ - 지정 범위 안 int형 난수 생성. (= ra…
module Python - random.choice() 메서드 ★★ - 요소 랜덤 반환. (= choice메서드 = 초…
module Python - random.choices() 메서드 - 가중치 반영해 랜덤 요소 반환. (= choices…
module Python - random.shuffle() 메서드 ★★ - 요소 순서 뒤섞기. (= 순서 랜덤 = shu…
module Python - random.sample() 메서드 ★ - 일부 요소 랜덤 선택. (= sample메서드 =…
module Python - random.random() 메서드 ★ - 0 ~ 1 사이 부동소수 랜덤 반환. (= ran…
module Python - random.uniform() 메서드 ★ - 지정 범위 안 랜덤 부동소수 반환. (= uni…
module Python - random.triangular() 메서드 - 지정 범위 안 가중치 반영 랜덤 부동소수 반환…
module Python - random.betavariate() 메서드 △ - 베타분포 (통계용) 기반 0~1 사이 랜…
module Python - random.expovariate() 메서드 △ - 지수분포 (통계용) 기반 랜덤 부동소수 …
module Python - random.gammavariate() 메서드 △ - 감마분포 (통계용) 기반 랜덤 부동소수…
module Python - random.gauss() 메서드 △ - 가우스분포 (확률이론용) 기반 랜덤 부동소수 반환.
module Python - random.lognormvariate() 메서드 △ - 로그정규분포 (확률이론용) 기반 랜…
4/24
목록
찾아주셔서 감사합니다. Since 2012