[NoSQL] MongoDB Shell

3 minute read


MongoDB Shell

  • MongoDB Shell Overall
  • MongoDB Shell Find
  • MongoDB Shell Update & Remove & Drop
  • MongoDB Shell Aggregate

MongoDB Shell Overall

# 접속
mongosh -u "root" -p "1234" 

# show all DB
show dbs;

# db 생성 및 해당 db로 접속 (use [db_name])
use testDB;

# 현재 접속해있는 db 삭제
db.dropDatabase();

# collection 만들기
db.createCollection("user");

# user collection(rdbms:table)에 documents(row) 추가
db.user.insertMany([
  {uName: "Tom", pwd: "1111", age: 20},
  {uName: "Jane", pwd: "2222", age: 30},
]);

# document 추가
db.user.insertOne({uName: "zsu", pwd: "6666"});

# 전체 documents 보기
db.user.find();

# uName이 Tom인 row 보기
db.user.find({uName:"Tom"});

# uName이 Jane인 document의 비밀번호 4444로 바꾸기
db.user.update({uName:"Jane"}, {$set: {pwd:4444}});

# uName이 Jane인 document 삭제
db.user.deleteOne({uName:"Jane"});

MongoDB Shell Find

# collection 만들기
db.createCollection("score");

# document 추가
db.score.insertMany(
  {name: "Sophia", point:99},
  {name: "Alice", point:85},
  {name: "Jane", point:76},
  {name: "James", point:64},
);

# 미리 list을 만들어두고 추가
var names = ["Jane", "Tom", "Alice", "James", "Sophia"];
var points = [76,54,85,64,99];
for (i=0; i<names.length; i++){
  db.score.insertOne({name:names[i], point:points[i]});
  };

# point가 90점 초과인 데이터 찾기
db.score.find({point:{$gt:90}});

# point가 70점 초과인 첫 번째 데이터 찾기
db.score.findOne({point:{$gt:70}});

# point가 60점 이상 90졈 이하인 데이터 찾기
db.score.find({point:{$gte:60, $lte:90}});
# 위와 같음
db.score.find({point:{$gte:60}, point:{$lte:90}});

# point가 54, 76, 99점 중 있는 데이터 찾기
db.score.find({point:{$in:[54,76,99]}});

# point가 54, 76, 99점 외의 데이터 찾기
db.score.find({point:{$nin:[54,76,99]}});

# point가 60 이하 or 90 이상인 데이터만 찾기
db.score.find(
  {
    $or:[
      {point:{$lte:60}},{point:{$gte:90}}
      ]
  }
);

# point column이 있는 document 찾기
db.score.find({point:{$exists:true}});

# point column이 없는 document 찾기
db.score.find({age:{$exists:false}});

# db.collection.find({condition},{column:0/1}), 0=don't show, 1=show
# point가 76점 이상인 document의 이름만 찾기
db.score.find({point:{$gte:76}},{_id:0, name:1});

# limit query result to 2
db.score.find().limit(2);

# skip two document
db.score.find().skip(2);

# sort by point(ascending)
db.score.find().sort({point:1});

# sort by point(descending)
db.score.find().sort({point:-1});

# document 중 name이 Jane이면서 certi column이 있는 document 제거
db.score.deleteOne({name:"Jane", certi:{$exists:true}});

MongoDB Shell Update & Remove & Drop

db.test.insertMany(
  [
    {name:"Jane", certi:["Java", "OS", "Excel"]},
    {name:"Tom", certi:["DB", "Secuity"]},
    {title:"IT Trend", author:"James", price:5000},
    {name:"Alice", certi:["PPT", "SQL", "Web"]},
    {name:"John", age:34}
  ]
);

# name이 John인 document의 age column 삭제
db.score.update({name:"John"},{$unset:{age:34}});

# title이 IT Trend인 document에서 price: 35000이라는 column 추가
db.score.update({title:"IT Trend"},{$set:{price:35000}});

# title이 IT Trend인 document에서 price: 35000에서 70000으로 변경
db.score.update({title:"IT Trend"},{$set:{price:70000}});

# name이 John인 document에서 cert:["OS", "DB"]이라는 column 추가
db.score.update({name:"John"},{$set:{certi:["OS", "DB"]}});

# name이 John인 document에서 cert column에 Word 추가
db.score.update({name:"John"},{$push:{certi:"Word"}});

# name이 John인 document에서 cert column에 Word 제거
db.score.update({name:"John"},{$pull:{certi:"Word"}});

# name이 Jane인 document 제거
db.score.remove({name:"Jane"});

# collection의 documents 삭제
db.score.remove({});

# collection 삭제
db.score.drop();

MongoDB Shell Aggregate

# select deptno, and dname
db.dept.aggregate([
  {"$project": {"_id": 0, "deptno": 1, "dname": 1}}
]);

# select deptno, and dname, and limit the data to 3
db.dept.aggregate([
  {"$project": {"_id": 0, "deptno": 1, "dname": 1}}, {"$limit": 2}
]);

# count all documents in dept collection
db.dept.aggregate([
  {"$group": {"_id": 0, "count": {"$sum":1}}}
])

# count employees by deptno
db.emp.aggregate([
  {"$group": {"_id": "$deptno", "count": {"$sum": 1}}}
])

# sum of salary by deptno
db.emp.aggregate([
  {"$group": {"_id": "$deptno", "count": {"$sum": "$sal"}}}
])

# mean of salary by job
db.emp.aggregate([
  {"$group": {"_id": "$job", "count": {"$avg": "$sal"}}}
])

# round mean of salary by job
db.emp.aggregate([
  {"$group": {"_id": "$job", "avg":{"$avg": "$sal"}}}, 
  {"$addFields": {"avg": {"$round":["$avg", -1]}}} 
])

# dept collection을 기준으로 emp collection join 한 뒤 dept_emp_join이라는 collection에 저장
# from - join될 collection name (emp)
# localField - dept collection의 기준 field
# foreignField - emp collection의 기준 field
# as - 기준 collection(dept)에 새로운 filed가 만들어지며 해당 filed 아래에 기준에 맞는 emp collection의 object이 들어감
db.dept.aggregate([
  {
    "$lookup":
      {
        "from": "emp", 
        "localField": "deptno", 
        "foreignField": "deptno", 
        "as": "dno"
      }
  },
  {"$out": "dept_emp_join"}
])

# dname 개수
db.dept_emp_join.aggregate(
  {"$group": {"_id": 0, "count":{"$sum":1}}}
)

# dname별 인원 수
db.dept_emp_join.aggregate(
  {"$unwind": "$dno"},
  {"$group": {"_id": "$dname", "count":{"$sum":1}}}
)
# 다른 방법
db.dept_emp_join.aggregate(
  {"$group": {"_id": "$dname", "count":{"$sum": {"$size":"$dno"}}}}
)


# dname 별 급여 합계
db.dept_emp_join.aggregate(
  {"$unwind": "$dno"},
  {"$group": {"_id": "$dname", "sum":{"$sum": "$dno.sal"}}}
)
# 다른 방법
db.dept_emp_join.aggregate(
  {"$group": {"_id": "$dname", "sum":{"$sum": {"$sum": "$dno.sal"}}}}
)

# Accounting 부서 소속 직원들의 사번, 이름, 급여는? 급여를 기준으로 ascending하게 sort, (descending일 경우 -1)
db.dept_emp_join.aggregate(
  {"$match": {"dname": "ACCOUNTING"}},
  {"$project": {"_id":0, "dno.empno": 1, "dno.ename": 1, "dno.sal": 1}},
  {"$sort": {"dno.sal": 1}}
)

ref