반응형
Databse
DB 목록 조회
show dbs;
DB 전환
- dev라는 이름의 Database로 전환
use dev;
선택된 DB 조회
db;
db.getName();
DB 삭제
- 현재 선택된 DB 삭제
db.dropDatabase();
User
사용자 조회
show users
사용자 생성
// test_db로 전환
use test_db
// test_db에 readWrite 권한의 사용자 추가
db.createUser({
user: 'test_user',
pwd: 'test_pw',
roles: ['readWrite']
})
사용자 삭제
db.dropUser('test_user')
Collection
컬렉션 조회
- 컬렉션 : RDBMS의 테이블
show collections;
컬렉션 생성
db.createCollection("student");
컬렉션 삭제
db.student.drop();
기타
자바스크립트 코드 실행
a = 5;
a * 10;
var a = { age : 25 };
print("Hello");
데이터 저장
db.scores.insertOne({ a : 99 });
for (i = 0; i < 10; i++) { db.scores.insertOne({ a: i, exam: 5 }); };
db.scores.insertMany([
{a: 45},
{a: 86},
])
데이터 조회
// 전체 조회
db.scores.find();
// 실행 시간 및 실행 계획 확인
db.scores.find().explain();
// 데이터 개수 조회
db.scores.count();
// a가 2인 데이터 조회
db.scores.find({ a : 2 });
// a가 2가 아닌 데이터 조회
db.scores.find({ a : { $ne: 2 } });
// a가 2보다 크고 4보다 작은 데이터 조회
db.scores.find({ a: { "$gte": 2, "$lte": } });
// 2, 3, 4중에 존재하는 데이터 조회
db.scores.find({ a: { "$in": [2, 3, 4] } });
// 2, 3, 4를 제외한 데이터 조회
db.scores.find({ a: { "$nin": [2, 3, 4] } });
// a가 2보다 작거나 4보다 큰 데이터 조회
db.scores.find({ "$or": [ { a: { "$lt": 2 } }, { a: { "$gt": 4 } } ] });
// a가 2보다 작거나 4보다 큰 데이터를 제외하고 조회
db.scores.find({ "$nor": [ { a: { "$lt": 2 } }, { a: { "$gt": 4 } } ] });
// exam 필드가 존재하는 데이터 조회
db.scores.find({ exam: { $exists: true } });
// a, exam 필드만 조회
db.scores.find({ a: { $in: [2, 3, 4] } }, { a: 1, exam: 1, _id: 0 });
// a 필드 기준 내림차순 정렬
db.scores.find().sort({ a: -1 });
// regex 조회
db.students.find({ name: { $regex: "john" } });
// 특정 필드 distinct 조회
db.students.distinct('name');
데이터 수정
// 키 a가 0인 데이터 전체 수정
db.scores.update({ a: 0 }, { a: 100, exam: 10 }, { multi: true });
// upsert
db.scores.update({ a: 0 }, { a: 100, exam: 10 }, { multi: true, upsert: true });
// 키 a가 0인 데이터의 특정 필드만 수정
db.scores.update({ a: 0 }, { $set: { exam: 10 } }, { multi: true });
// 키 a가 0인 데이터의 특정 필드 제거
db.scores.update({ a: 0 }, { $unset: { exam: 0 } }, { multi: true });
// name: john인 데이터의 languages 리스트 필드의 값 중에서 'java'를 제거
db.users.update({ name: 'john' }, { $pull: { languages: 'java' } }, { multi: true });
// name: john인 데이터의 languages 리스트 필드에 'java' 추가
db.users.update({ name: 'john' }, { $push: { languages: 'java' } }, { multi: true });
// 대량 데이터 upsert
db.users.bulkWrite([
{
updateOne: {
filter: { name: 'john' },
update: { $setOnInsert: { name: 'john', language: 'java' } },
upsert: true
}
},
...
]);
데이터 수정 - bulk
var bulk = db.students.initializeUnorderedBulkOp();
db.students.find().forEach((doc) => {
const newDoc = {
name: doc.name,
age: doc.age,
deleted: false
};
bulk.find({ _id: doc._id }).updateOne(newDoc);
});
bulk.execute();
데이터 복사
// MY_DB 데이터베이스의 students 컬렉션을 MY_DB_DEV 데이터베이스의 students 컬렉션으로 복사
db.students.find().forEach((document) => db.getSiblingDB('MY_DB_DEV').students.insert(document))
데이터 삭제
// collection 삭제
db.users.drop();
// 전체 데이터 삭제
db.users.remove({});
// name: john인 데이터 삭제
db.users.remove({ name: 'john' });
인덱스 확인
db.scores.getIndexes();
인덱스 추가
// a키를 기준으로 오름차순으로 인덱싱 (오름차순: 1, 내림차순: -1)
db.scores.ensureIndex({ a: 1 });
// 인덱싱 작업을 백그라운드로 처리, foreground 인덱싱보다 성능이 떨어짐
db.scores.ensureIndex({ a: 1 }, { background: true });
// unique 인덱스 생성
db.scores.ensureIndex({ a: 1 }, { unique: true });
// 중복 데이터가 기존에 있을 경우 기존 데이터를 삭제 후 신규 데이터 저장 가능
db.scores.ensureIndex({ a: 1 }, { unique: true, dropDups: true });
인덱스 삭제
// 특정 인덱스 삭제
db.scores.dropIndex({ a: 1 });
// 모든 인덱스 삭제 (_id는 제외)
db.scores.dropIndexes();
참고
- https://www.youtube.com/watch?v=-l9A5V6vzKQ&list=PL9mhQYIlKEheyXIEL8RQts4zV_uMwdWFj&index=7
반응형
'Development > MongoDB' 카테고리의 다른 글
[MongoDB] Spring 연동 (0) | 2020.12.29 |
---|---|
[MongoDB] NodeJS 연동 (0) | 2020.12.29 |
[MongoDB] 데이터 백업/복구 (0) | 2020.12.29 |
[MongoDB] Replica Set 구성하기 (0) | 2020.12.29 |
[MongoDB] 설치하기 (0) | 2020.12.29 |