본문 바로가기
DB/MongoDB

데이터 베이스(No SQL) - MongoDB 데이터 삽입 (Insert)

by nomfang 2021. 1. 22.
728x90
반응형

MongoDB Insert

MongoDB 파이썬에서 생성된 컬렉션에 도큐먼트를 생성하는 방법은 기본적으로 2가지 

1. insert_one() 메소드 사용하여 생성하기

#문법 collection.insert_one( 컬렉션에 삽입할 도큐먼트 혹은 변수 ) 
#예시 mycol = mydb["customers"] 

mydict = { 
"name": "John", "address": "Highway 37" 
} 
x = mycol.insert_one(mydict)

2. insert_many()메소드 사용하여 생성하기

#문법 collection.insert_many( 컬렉션에 삽입한 도큐먼트 혹은 변수)



#예시 mycol = mydb["customers"]

mylist = [ {

"name": "Amy", "address": "Apple st 652"}, 
{ "name": "Hannah", "address": "Mountain 21"}, 
{ "name": "Michael", "address": "Valley 345"}, 
{ "name": "Sandy", "address": "Ocean blvd 2"}, 
{ "name": "Betty", "address": "Green Grass 1"}, 
{ "name": "Richard", "address": "Sky st 331"}, 
{ "name": "Susan", "address": "One way 98"}, 
{ "name": "Vicky", "address": "Yellow Garden 2"}, 
{ "name": "Ben", "address": "Park Lane 38"}, 
{ "name": "William", "address": "Central st 954"}, 
{ "name": "Chuck", "address": "Main Road 989"}, 
{ "name": "Viola", "address": "Sideway 1633"

} ]

x = mycol.insert_many(mylist)

💡 Tip!
MongoDB 쉘에서는 insert(), insertOne(), insertMany() 메소드를 이용해서 데이터를 삽입
insertOne()은 하나의 도큐먼트 삽입
insertMany()는 여러개의 도큐먼트 삽입
insert()는 두 가지 모두 가능

import pymongo 
from pprint import pprint 


connection = pymongo.MongoClient("mongodb://localhost:27017/") 
db = connection["library"] 
col = db["books"] 

# 데이터를 만들고 삽입하세요. 
data = col.insert_one({ 
    "title": "Romeo and Juliet", 
    "author": "William Shakespeare", 
    "date_received": "2012-04-01" 
})



## id를 이용해서 데이터 출력하기

pprint(col.find_one({"_id": data.inserted_id}))
반응형

댓글