🌱MongoDB In 30 Minutes

yeeun lee·2020년 8월 11일

설치는 공식문서, command는 MongoDB In 30 Minutes by Traversy Media channel 유튜브 영상을 참고했다.

1. 설치(mac ver.)

링크에 간단한 가이드가 나와있다. community edition을 설치하면 되고, 설치하기 전 맥 기준으로 xcode, brew가 깔려 있어야 한다.

위 두개가 설치된 것을 기준으로 아래 명령어를 터미널에 입력하면 설치되고 이후 mongo를 입력하면 db를 실행할 수 있다.

brew tap mongodb/brew
brew install mongodb-community@4.4

나는 xcode를 쓰지도 않고 괜히 용량만 차지하는 것 같아서 지우고 있다가 계속 오류가 발생했다. 앱스토어에서 다시 깔았는데 시간이 왜이렇게 오래 걸리는지...😑

2. mongoDB

2.1 특징

  • document type of nosql
  • stores data records as BSON documents. BSON is a binary representation of JSON document
  • don't need pre-defined structures like RDBMS's schema, tables, data type settings, etc
  • easy to scale
  • much faster in most types of operations
  • can have whatever fields you want, whatever documents you want

2.2 개념

- collection

관계형 데이터베이스의 테이블과 유사한 개념. Document & record를 가지고 있다.

- document

하나의 record이며, field:value로 구성되어 있다. (이미지 출처: 공식문서)

- ObjectId

uniqe value로서 document를 찾는 용도 등으로 사용되고 자동 생성된다. 관계형 데이터베이스처럼 auto-increment되는 primary key가 없어도 되는 이유!

- object & array

python을 쓰다가 보니까 헷갈려서, {}가 객체=object, []가 배열=array다.

3. command

3.1 CRUD

db.createUser() 관련 공식 문서 설명, 반드시 모든 key값을 가질 필요는 없다. 필요에 따라서 구성하면 됨!

// user 만들기
> db.createUser({
... user:"yeni",
... pwd:"1234",
... roles: ["readWrite", "dbAdmin"]
... });

// collection 생성
> db.createCollection('customers'); 
{ "ok" : 1 }

// collections 조회
> show collections 
customers

- insert

// 데이터 넣기
> db.customers.insert({first_name:"Yeeun", last_name:"Lee"}); 
WriteResult({ "nInserted" : 1 })


// 복수의 데이터 넣기: array 안에! 
> db.customers.insert([{first_name:"John", last_name:"Doe"}, 
                      {first_name:"Steven", last_name:"Smith", gender:"male"}]);
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})

upsert

없는 field를 업데이트할 경우 아무 결과도 반영되지 않지만, upsert option을 추가하면 데이터가 추가된다.

> db.customers.update({first_name:"Mary"}, 
                      {first_name:"Mary", last_name:"Samson"},
                      {upsert:true}); // upsert = true 설정
WriteResult({
	"nMatched" : 0,
	"nUpserted" : 1,
	"nModified" : 0,
	"_id" : ObjectId("5f32758fbf762656882f2068")
})

> db.customers.find().pretty();
{
	"_id" : ObjectId("5f32758fbf762656882f2068"),
	"first_name" : "Mary",
	"last_name" : "Samson"
}

- find

// 조회 
> db.customers.find();
{ "_id" : ObjectId("5f325e13a7405fe8dbb33b91"), "first_name" : "Yeeun", "last_name" : "Lee" }

// 예쁘게(?) 조회 
> db.customers.find().pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee"
}

// 이름이 Yeeun인 고객 찾아줘
> db.customers.find({first_name:"Yeeun"}).pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female"
}

- update

아래의 방법을 쓰면 first_name이 John인 모든 데이터를 바꿔버린다. 그래서 보통 Unique value를 사용하지만, first_name John이 중복되지 않고 있어 강의에서는 first_name으로 record를 선택했다.

// first_name이 John인 record를 다음 {}로 바꿔줘! 
> db.customers.update({first_name:"John"}, 
                      {first_name:"John", last_name:"Doe", gender:"male"});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.customers.find().pretty();
{
	"_id" : ObjectId("5f3261fca7405fe8dbb33b92"),
	"first_name" : "John",
	"last_name" : "Doe",
	"gender" : "male" // 성별이 추가되었다. 
}

- remove

아래 특정 field를 넣으면 해당 key, value를 가진 record가 지워지고, 빈 curly bracket을 넣으면 collection 전체가 지워진다.

> db.customers.remove({first_name:"John"});
WriteResult({ "nRemoved" : 1 })

with parameter

지울 때 하나만 지우는 옵션

> db.customers.remove({first_name:"Steven"}, {justOne:true});
WriteResult({ "nRemoved" : 0 })

3.2 operators

공식 문서 참고 ✔️

- Query and Projection Operators

logical

  • and
  • not
  • nor
  • or
// 이름이 Yeeun이거나 John인 고객 찾아줘 
> db.customers.find( {$or:[{first_name:"Yeeun"}, {first_name:"John"}]} ).pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female"
}
{
	"_id" : ObjectId("5f3261fca7405fe8dbb33b92"),
	"first_name" : "John",
	"last_name" : "Doe",
	"gender" : "male"
}

comparison

  • $gt: greater than
  • $gte: greater than or equal to
  • $lt: less than
  • $lte: less than or equal to
// 나이가 35보다 큰 고객 찾아줘 
> db.customers.find({age:{$gt:35}}).pretty(); // greater than
{
	"_id" : ObjectId("5f32758fbf762656882f2068"),
	"first_name" : "Mary",
	"last_name" : "Samson",
	"gender" : "female",
	"age" : 40
}

// 나이가 35보다 작은 고객 찾아줘 
> db.customers.find({age:{$lt:35}}).pretty(); // less than
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female",
	"age" : 30
}

- Update Operators

$set

update에서 record 선택 후 모든 key, value를 입력해야 하는 것과 달리 $set을 사용하면 추가하고자 하는 key, value만 넣을 수 있다.

> db.customers.update({first_name:"Yeeun"}, {$set:{gender:"female"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.customers.find().pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female" // 성별만 추가되었다.
}

$unset

특정 field를 지워준다. 1은 json/bson syntax로 특별한 의미는 없고 value가 있어야 하기 때문에 그냥 넣어준 것(typicaly use)이라고 이해하면 된다.


// age field 삭제
> db.customers.update({first_name:"Yeeun"}, {$unset:{age:1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.customers.find().pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female"
}

3.3 advanced

- javascript function

반복문을 돌릴 수 있다 😮 sql도 찾아보면 비슷한 기능이 있겠지만, javascript 기반 데이터베이스다보니 javascript function을 써서 좀 신기...!

> db.customers.find().forEach(function(doc){print("Customer Name:" + doc.first_name)});
Customer Name:Yeeun
Customer Name:John
Customer Name:Mary

- value 안의 value 찾기

address key 안에 또 object가 있는데, 요거를 Dot notation으로 접근! key값에도 ""(quote)를 쓰는 client나 program이 있으니 확인하고 쓸 것

> db.customers.find({"address.state":"MA"}).pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female",
	"age" : 30,
	"address" : {
		"street" : "411 Blue st",
		"city" : "Boston",
		"state" : "MA"
	}
}

- 숫자 value 증가시키기

숫자 value를 update command를 통해 증가시키는 방법 !

> db.customers.update({first_name:"Yeeun"}, {$inc:{age:1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.customers.find().pretty();
{
	"_id" : ObjectId("5f325e13a7405fe8dbb33b91"),
	"first_name" : "Yeeun",
	"last_name" : "Lee",
	"gender" : "female",
	"age" : 31
}
{
	"_id" : ObjectId("5f3261fca7405fe8dbb33b92"),
	"first_name" : "John",
	"last_name" : "Doe",
	"gender" : "male"
}
{
	"_id" : ObjectId("5f3261fca7405fe8dbb33b93"),
	"first_name" : "Steven",
	"last_name" : "Smith",
	"gender" : "male"
}

- key값 바꾸기

> db.customers.update({first_name:"Steven"}, 
                      {$rename: {"gender":"sex"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.customers.find().pretty();
{
	"_id" : ObjectId("5f3261fca7405fe8dbb33b93"),
	"first_name" : "Steven",
	"last_name" : "Smith",
	"sex" : "male" // key값이 바뀌었다
}

- sorting

sort parameter의 value에서 1은 ascending, -1은 descending option

> db.customers.find().sort({first_name:1});

- 그 외

  • db.customers.find().limit(4); : 4개만 보여줘
  • db.customers.find().count(); : 몇개야?
profile
이사간 블로그: yenilee.github.io

0개의 댓글