1. Document 입력 - insertOne, insertMany
- insertOne: 한 개의 document(문서)를 생성
- insertMany: 여러 개의 document를 한 번에 생성
// 하나의 문서를 추가 (insertOne)
db.test_2.insertOne(
{ title: "MongoDB Guide", author: "Jane Doe", views: 100 }
)
// 여러 개의 문서를 추가 (insertMany)
db.test_2.insertMany([
{ title: "Python Tutorial", author: "John Smith", views: 150 },
{ title: "JavaScript Basics", author: "Sara Lee", views: 200 },
{ title: "Node.js in Action", author: "Mike Brown", views: 250 }
])
2. Document 읽기(검색) - findOne, find
- findOne: 조건에 맞는 한 개의 document를 검색
- find: 조건에 맞는 여러 개의 document를 검색
// 하나의 문서를 검색 (findOne)
db.test_2.findOne({ title: "MongoDB Guide" })
// 조건에 맞는 모든 문서를 검색 (find)
db.test_2.find({ views: { $gte: 150 } })
// 특정 필드만 출력 (projection)
db.test_2.find({ views: { $gte: 150 } }, { title: 1, author: 1, _id: 0 })
3. Document 수정 - updateOne, updateMany
- updateOne: 조건에 맞는 한 개의 document를 업데이트
- updateMany: 조건에 맞는 여러 개의 document를 업데이트
// 한 개의 문서를 업데이트 (updateOne)
db.test_2.updateOne({ title: "MongoDB Guide" }, { $set: { views: 120 } })
// 조건에 맞는 여러 문서를 업데이트 (updateMany)
db.test_2.updateMany({ author: "John Smith" }, { $set: { author: "Jonathan Smith" } })
4. Document 삭제 - deleteOne, deleteMany
- deleteOne: 조건에 맞는 한 개의 document를 삭제
- deleteMany: 조건에 맞는 여러 개의 document를 삭제
// 한 개의 문서를 삭제 (deleteOne)
db.test_2.deleteOne({ title: "Node.js in Action" })
// 조건에 맞는 여러 문서를 삭제 (deleteMany)
db.test_2.deleteMany({ views: { $lt: 150 } })
MongoDB의 다양한 문법
정규 표현식 ($regex)
db.test_2.find({ name: { $regex: /^b/ } }) // name이 'b'로 시작하는 문서들을 조회하는 방법
db.test_2.find({ name: { $regex: /apple$/ } }) // name이 'apple'로 끝나는 문서들을 조회하는 방법
정렬 (.sort())
db.test_2.find().sort({ stock: 1 }) // stock 필드를 기준으로 오름차순 정렬하는 방법
db.test_2.find().sort({ name: -1 }) // name 필드를 기준으로 내림차순 정렬하는 방법
문서 개수 세기 (.countDocuments(), .estimatedDocumentCount())
db.test_2.countDocuments({ category: "fruit" }) // 특정 조건(category가 "fruit")을 만족하는 문서의 개수를 세는 방법
db.test_2.estimatedDocumentCount() // 컬렉션 내 전체 문서의 개수를 추정하는 방법
필드 존재 여부 확인 ($exists)
db.test_2.find({ price: { $exists: true } }) // 특정 필드(price)가 존재하는 문서들을 조회하는 방법
db.test_2.find({ discount: { $exists: false } }) // 특정 필드(discount)가 존재하지 않는 문서들을 조회하는 방법
중복 제거 (.distinct())
db.test_2.distinct("category") // 특정 필드(category)의 중복을 제거하고 고유한 값을 조회하는 방법
리미티드와 스킵 (.limit(), .skip())
db.test_2.find().limit(5) // 조회 결과에서 처음 5개의 문서만 가져오는 방법
db.test_2.find().skip(2) // 조회 결과에서 처음 2개의 문서를 건너뛰고 가져오는 방법
집계 (.aggregate())
db.test_2.aggregate([
{ $match: { category: "fruit" } }, // 특정 조건(category가 "fruit")을 만족하는 문서를 필터링하는 방법
{ $group: { _id: "$category", totalStock: { $sum: "$stock" } } }
]) // 필터링된 문서들을 그룹화하여 category별 총 stock 합계를 계산하는 방법
데이터베이스 및 컬렉션 관리
show dbs // 모든 데이터베이스 목록 보기
use test // 특정 데이터베이스 사용 (없으면 생성)
show collections // 현재 데이터베이스의 컬렉션 목록 보기
db.stats() // 현재 데이터베이스의 통계 정보 확인
db.dropDatabase() // 현재 데이터베이스 삭제
db.test_2.drop() // 특정 컬렉션(test_2) 삭제
db.createCollection("test_5", { capped: true, size: 1234, max: 100 }) // 새로운 컬렉션 생성 (크기 및 문서 수 제한)
db.test_5.renameCollection("test_6") // 컬렉션 이름 변경
비교 및 논리 연산자
// 비교 연산자 예제
db.test_2.find({ quantity: { $eq: 10 } }) // 특정 값과 같은 값 매칭
db.test_2.find({ quantity: { $gt: 5 } }) // 특정 값보다 큰 값 매칭
db.test_2.find({ quantity: { $gte: 15 } }) // 특정 값보다 크거나 같은 값 매칭
db.test_2.find({ item: { $in: ["banana", "mango"] } }) // 배열에 지정된 값들 중 하나와 매칭
db.test_2.find({ quantity: { $lt: 10 } }) // 특정 값보다 작은 값 매칭
db.test_2.find({ quantity: { $lte: 8 } }) // 특정 값보다 작거나 같은 값 매칭
db.test_2.find({ quantity: { $ne: 10 } }) // 특정 값과 같지 않은 값 매칭
db.test_2.find({ item: { $nin: ["apple", "orange"] } }) // 배열에 지정된 값들 중 어느 것도 매칭되지 않음
// 논리 연산자 예제
db.test_2.find({ $or: [ // 여러 조건 중 하나라도 만족하는 문서 매칭
{ item: "apple" },
{ quantity: { $gt: 10 } }
] })
db.test_2.find({ $and: [ // 모든 조건을 만족하는 문서 매칭
{ item: "banana" },
{ quantity: { $lt: 15 } }
] })
db.test_2.find({ item: { $not: { $eq: "mango" } } }) // 조건을 만족하지 않는 문서 매칭
비교 연산자
- $eq: 특정 값과 같은 값들을 매칭
- $gt: 특정 값보다 큰 값들을 매칭
- $gte: 특정 값보다 크거나 같은 값들을 매칭
- $in: 배열에 지정된 값들 중 하나와 매칭
- $lt: 특정 값보다 작은 값들을 매칭
- $lte: 특정 값보다 작거나 같은 값들을 매칭
- $ne: 특정 값과 같지 않은 값들을 매칭
- $nin: 배열에 지정된 값들 중 어느 것도 매칭되지 않음
논리 연산자
- $or: 여러 조건 중 하나라도 만족하는 문서 매칭
- $and: 모든 조건을 만족하는 문서 매칭
- $not: 조건을 만족하지 않는 문서 매칭