티스토리 뷰

MongoDB

[MongoDB] Mongo Shell Baseic

SchoolDevops 2022. 4. 14. 15:17

Mongo Shell Baseic

  • 이번에는 mongod shell에 접근하여 간단한 CRUD를 실행해 볼 것이다.

mongo shell 이용하기.

  • mongo shell을 이용하기 위해서는 로컬에 mongodb를 설치하여 shell을 실행하는 방법이 있다.
  • 여기서는 docker 컨테이너에 접근하여 mongo shell을 실행해 보자.
docker ps 

CONTAINER ID   IMAGE             COMMAND                  CREATED       STATUS       PORTS                               NAMES
d9793501e971   mongo             "docker-entrypoint.s…"   2 hours ago   Up 2 hours   0.0.0.0:27017->27017/tcp            mongodb
7e7b0ad839d4   mongo-express     "tini -- /docker-ent…"   2 hours ago   Up 2 hours   0.0.0.0:8081->8081/tcp              mongo-express
  • 우리는 여기서 위 CONTAINER_ID d9793501e971 를 이용할 것이다.
docker exec -it d9793501e971 /bin/bash
  • 그리고 다음과 같이 mongo shell 명령을 수행한다.
root@d9793501e971:/# mongo mongodb://localhost:27017 -u rootuser -p rootpass

MongoDB shell version v5.0.6
connecting to: mongodb://localhost:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("68ac0b3f-5528-4d4e-94fd-6c4994293987") }
MongoDB server version: 5.0.6
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
---
The server generated these startup warnings when booting: 
        2022-03-20T23:57:42.068+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 

Basic Mongo Shell

데이터베이스 보기

> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

데이터베이스 사용하기.

> use kidodb
switched to db kidodb

> db.getName();
kidodb

Collection 생성하기

> db.createCollection("hello");
{ "ok" : 1 }

> show dbs;
admin   0.000GB
config  0.000GB
kidodb  0.000GB
local   0.000GB

DB 삭제하기

> db.dropDatabase();
{ "ok" : 1 }

> show dbs;
admin   0.000GB
config  0.000GB
local   0.000GB

Mongo DB 메소드 알아보기

> db.help()
DB methods:
    db.adminCommand(nameOrDocument) - switches to 'admin' db, and runs command [just calls db.runCommand(...)]
    db.aggregate([pipeline], {options}) - performs a collectionless aggregation on this database; returns a cursor
    db.auth(username, password)
    db.commandHelp(name) returns the help for the command
    db.createUser(userDocument)
    db.createView(name, viewOn, [{$operator: {...}}, ...], {viewOptions})
    db.currentOp() displays currently executing operations in the db
    db.dropDatabase(writeConcern)
    db.dropUser(username)
    db.eval() - deprecated
    db.fsyncLock() flush data to disk and lock server for backups
    db.fsyncUnlock() unlocks server following a db.fsyncLock()
    db.getCollection(cname) same as db['cname'] or db.cname
    db.getCollectionInfos([filter]) - returns a list that contains the names and options of the db's collections
    db.getCollectionNames()
    db.getLastError() - just returns the err msg string
    db.getLastErrorObj() - return full status object
    db.getLogComponents()
    db.getMongo() get the server connection object
    db.getMongo().setSecondaryOk() allow queries on a replication secondary server
    db.getName()
    db.getProfilingLevel() - deprecated
    db.getProfilingStatus() - returns if profiling is on and slow threshold
    db.getReplicationInfo()
    db.getSiblingDB(name) get the db at the same server as this one
    db.getWriteConcern() - returns the write concern used for any operations on this db, inherited from server object if set
    db.hostInfo() get details about the server's host
    db.isMaster() check replica primary status
    db.hello() check replica primary status
    db.killOp(opid) kills the current operation in the db
    db.listCommands() lists all the db commands
    db.loadServerScripts() loads all the scripts in db.system.js
    db.logout()
    db.printCollectionStats()
    db.printReplicationInfo()
    db.printShardingStatus()
    db.printSecondaryReplicationInfo()
    db.rotateCertificates(message) - rotates certificates, CRLs, and CA files and logs an optional message
    db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into {cmdObj: 1}
    db.serverStatus()
    db.setLogLevel(level,<component>)
    db.setProfilingLevel(level,slowms) 0=off 1=slow 2=all
    db.setVerboseShell(flag) display extra information in shell output
    db.setWriteConcern(<write concern doc>) - sets the write concern for writes to the db
    db.shutdownServer()
    db.stats()
    db.unsetWriteConcern(<write concern doc>) - unsets the write concern for writes to the db
    db.version() current version of the server
    db.watch() - opens a change stream cursor for a database to report on all  changes to its non-system collections.
> 

Collections

  • mongo는 document(row)를 collections(table)에 저장한다.

Collection 생성하기

> db.createCollection("person")
{ "ok" : 1 }

> show collections;
person

collection 삭제하기

> db.person.drop()
true

collection 상태 확인하기

> db.collection.stats()
{
        "ns" : "kidodb.collection",
        "size" : 0,
        "count" : 0,
        "storageSize" : 0,
        "totalSize" : 0,
        "nindexes" : 0,
        "totalIndexSize" : 0,
        "indexSizes" : {

        },
        "scaleFactor" : 1,
        "ok" : 1
}

collection 메소드

> db.collection.help()
DBCollection help
    db.collection.find().help() - show DBCursor help
    db.collection.bulkWrite( operations, <optional params> ) - bulk execute write operations, optional parameters are: w, wtimeout, j
    db.collection.count( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.collection.countDocuments( query = {}, <optional params> ) - count the number of documents that matches the query, optional parameters are: limit, skip, hint, maxTimeMS
    db.collection.estimatedDocumentCount( <optional params> ) - estimate the document count using collection metadata, optional parameters are: maxTimeMS
    db.collection.convertToCapped(maxBytes) - calls {convertToCapped:'collection', size:maxBytes}} command
    db.collection.createIndex(keypattern[,options])
    db.collection.createIndexes([keypatterns], <options>)
    db.collection.dataSize()
    db.collection.deleteOne( filter, <optional params> ) - delete first matching document, optional parameters are: w, wtimeout, j
    db.collection.deleteMany( filter, <optional params> ) - delete all matching documents, optional parameters are: w, wtimeout, j
    db.collection.distinct( key, query, <optional params> ) - e.g. db.collection.distinct( 'x' ), optional parameters are: maxTimeMS
    db.collection.drop() drop the collection
    db.collection.dropIndex(index) - e.g. db.collection.dropIndex( "indexName" ) or db.collection.dropIndex( { "indexKey" : 1 } )
    db.collection.hideIndex(index) - e.g. db.collection.hideIndex( "indexName" ) or db.collection.hideIndex( { "indexKey" : 1 } )
    db.collection.unhideIndex(index) - e.g. db.collection.unhideIndex( "indexName" ) or db.collection.unhideIndex( { "indexKey" : 1 } )
    db.collection.dropIndexes()
    db.collection.explain().help() - show explain help
    db.collection.reIndex()
    db.collection.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                    e.g. db.collection.find( {x:77} , {name:1, x:1} )
    db.collection.find(...).count()
    db.collection.find(...).limit(n)
    db.collection.find(...).skip(n)
    db.collection.find(...).sort(...)
    db.collection.findOne([query], [fields], [options], [readConcern])
    db.collection.findOneAndDelete( filter, <optional params> ) - delete first matching document, optional parameters are: projection, sort, maxTimeMS
    db.collection.findOneAndReplace( filter, replacement, <optional params> ) - replace first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.collection.findOneAndUpdate( filter, <update object or pipeline>, <optional params> ) - update first matching document, optional parameters are: projection, sort, maxTimeMS, upsert, returnNewDocument
    db.collection.getDB() get DB object associated with collection
    db.collection.getPlanCache() get query plan cache associated with collection
    db.collection.getIndexes()
    db.collection.insert(obj)
    db.collection.insertOne( obj, <optional params> ) - insert a document, optional parameters are: w, wtimeout, j
    db.collection.insertMany( [objects], <optional params> ) - insert multiple documents, optional parameters are: w, wtimeout, j
    db.collection.mapReduce( mapFunction , reduceFunction , <optional params> )
    db.collection.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
    db.collection.remove(query)
    db.collection.replaceOne( filter, replacement, <optional params> ) - replace the first matching document, optional parameters are: upsert, w, wtimeout, j
    db.collection.renameCollection( newName , <dropTarget> ) renames the collection.
    db.collection.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection name
    db.collection.save(obj)
    db.collection.stats({scale: N, indexDetails: true/false, indexDetailsKey: <index key>, indexDetailsName: <index name>})
    db.collection.storageSize() - includes free space allocated to this collection
    db.collection.totalIndexSize() - size in bytes of all the indexes
    db.collection.totalSize() - storage allocated for all data and indexes
    db.collection.update( query, <update object or pipeline>[, upsert_bool, multi_bool] ) - instead of two flags, you can pass an object with fields: upsert, multi, hint, let
    db.collection.updateOne( filter, <update object or pipeline>, <optional params> ) - update the first matching document, optional parameters are: upsert, w, wtimeout, j, hint, let
    db.collection.updateMany( filter, <update object or pipeline>, <optional params> ) - update all matching documents, optional parameters are: upsert, w, wtimeout, j, hint, let
    db.collection.validate( <full> ) - SLOW
    db.collection.getShardVersion() - only for use with sharding
    db.collection.getShardDistribution() - prints statistics about data distribution in the cluster
    db.collection.getSplitKeysForChunks( <maxChunkSize> ) - calculates split points over all chunks and returns splitter function
    db.collection.getWriteConcern() - returns the write concern used for any operations on this collection, inherited from server/db if set
    db.collection.setWriteConcern( <write concern doc> ) - sets the write concern for writes to the collection
    db.collection.unsetWriteConcern( <write concern doc> ) - unsets the write concern for writes to the collection
    db.collection.latencyStats() - display operation latency histograms for this collection
> 

컬렉션을 다양한 옵션을 통해서 생성한다.

> db.createCollection("person", { capped: true, size: 6142800, max: 30000 });
{ "ok" : 1 }

> db.collection.person.stats()
{
        "ns" : "kidodb.collection.person",
        "size" : 0,
        "count" : 0,
        "storageSize" : 0,
        "totalSize" : 0,
        "nindexes" : 0,
        "totalIndexSize" : 0,
        "indexSizes" : {

        },
        "scaleFactor" : 1,
        "ok" : 1
}
  • 컬렉션을 생성하고 확인하기
  • 'show collections;'를 이용하여 컬렉션 목록을 확인할 수 있다.
> db.createCollection("student")
{ "ok" : 1 }

> db.createCollection("person")
{ "ok" : 1 }

> show collections;
person
student

Documents

  • BSON 문서로 저장한다. B는 바이너리를 의미한다.
  • mongodb에서는 기본적으로 json을 이용하여 데이터, 쿼리, projection 등을 지정하게 된다.
  • 아래와 같이 json을 생성한다.
> student = {
    "firstName": "Kido",
    "lastName": "Bae", 
    "email": "baekido@gmail.com",
    "gender": "M",
    "useYn": false, 
    "subject": [
        "maths",
        "english",
        "it"
    ],
    "totalScore": 0.00
}

document 단건 인서트하기

- document 인서트 (단건 인서트)
> db.student.insert(student);
WriteResult({ "nInserted" : 1 })

- 인서트후 카운트 세기 
> db.student.count()
1

- 인서트한 내역을 확인하자. 
> db.student.find()
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae", "email" : "baekido@gmail.com", "gender" : "M", "country" : "Korea", "useYn" : false, "subject" : [ "maths", "english", "it" ], "totalScore" : 0 }

- pretty() 메소드를 이용하면 포맷된 형태로 볼 수 있다. 
> db.student.find().pretty()
{
        "_id" : ObjectId("6237c6a6c30fb6068b5cd258"),
        "firstName" : "Kido",
        "lastName" : "Bae",
        "email" : "baekido@gmail.com",
        "gender" : "M",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}


document 복수개 인서트하기

  • 배열 데이터 저장하기.
students = [
    {
        "firstName": "Ahyun",
        "lastName": "Bae", 
        "email": "ahyun@gmail.com",
        "gender": "F",
        "useYn": false, 
        "subject": [
            "maths",
            "english",
            "it"
        ],
        "totalScore": 0.00
    },
    {
        "firstName": "Aram",
        "lastName": "Bae", 
        "email": "aram@gmail.com",
        "gender": "F",
        "useYn": false, 
        "subject": [
            "maths",
            "english",
            "it"
        ],
        "totalScore": 0.00
    },
    {
        "firstName": "Aram1",
        "lastName": "Bae1", 
        "email": "aram1@gmail.com",
        "gender": "F",
        "useYn": false, 
        "subject": [
            "maths",
            "english",
            "it"
        ],
        "totalScore": 0.00
    },
    {
        "firstName": "Mama",
        "lastName": "Moo", 
        "email": "mamamoo@gmail.com",
        "gender": "F",
        "useYn": false, 
        "subject": [
            "maths",
            "english",
            "it"
        ],
        "totalScore": 0.00
    },
    {
        "firstName": "Gildong",
        "lastName": "Hong", 
        "email": "hong@gmail.com",
        "gender": "M",
        "useYn": false, 
        "subject": [
            "maths",
            "english",
            "it"
        ],
        "totalScore": 0.00
    }
]
  • 복수개의 데이터 인서트 insertMany 이용
> db.student.insertMany(students)
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("6237c7e6c30fb6068b5cd259"),
                ObjectId("6237c7e6c30fb6068b5cd25a"),
                ObjectId("6237c7e6c30fb6068b5cd25b"),
                ObjectId("6237c7e6c30fb6068b5cd25c"),
                ObjectId("6237c7e6c30fb6068b5cd25d")
        ]
}


find 로 검색하기

find 형식

db.users.find(                  <-- 컬렉션 이름 지정 
    { age: { $gt: 18 } },       <-- 검색 조건 json으로 작성 
    { name 1, address: 1 }      <-- 출력될 필드 
).limit(5)                      <-- 커서 제한

전체 내용 조회하기

  • 전체 내용 조회는 find() 만 이용하면 된다.
  • pretty() 메소드를 이용하면, 포맷된 json으로 출력한다.
> db.student.find().pretty()
{
        "_id" : ObjectId("6237c6a6c30fb6068b5cd258"),
        "firstName" : "Kido",
        "lastName" : "Bae",
        "email" : "baekido@gmail.com",
        "gender" : "M",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}
{
        "_id" : ObjectId("6237c7e6c30fb6068b5cd259"),
        "firstName" : "Ahyun",
        "lastName" : "Bae",
        "email" : "ahyun@gmail.com",
        "gender" : "F",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}
{
        "_id" : ObjectId("6237c7e6c30fb6068b5cd25a"),
        "firstName" : "Aram",
        "lastName" : "Bae",
        "email" : "aram@gmail.com",
        "gender" : "F",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}
{
        "_id" : ObjectId("6237c7e6c30fb6068b5cd25b"),
        "firstName" : "Aram1",
        "lastName" : "Bae1",
        "email" : "aram1@gmail.com",
        "gender" : "F",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}
{
        "_id" : ObjectId("6237c7e6c30fb6068b5cd25c"),
        "firstName" : "Mama",
        "lastName" : "Moo",
        "email" : "mamamoo@gmail.com",
        "gender" : "F",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}
{
        "_id" : ObjectId("6237c7e6c30fb6068b5cd25d"),
        "firstName" : "Gildong",
        "lastName" : "Hong",
        "email" : "hong@gmail.com",
        "gender" : "M",
        "country" : "Korea",
        "useYn" : false,
        "subject" : [
                "maths",
                "english",
                "it"
        ],
        "totalScore" : 0
}

document 카운트 세기

> db.student.find().pretty().count()
6

검색조건 이용하기.

검색 조건

  • 검색 조건으로 firstName이 Kido인 건을 찾는다.
> db.student.find({firstName: "Kido"}) 
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae", "email" : "baekido@gmail.com", "gender" : "M", "country" : "Korea", "useYn" : false, "subject" : [ "maths", "english", "it" ], "totalScore" : 0 }

프로젝션 하기

  • 출력 으로 firstName만 출력하기
  • 출력을 위해서는 필드 이름 : 1 로 세팅하면 된다.
> db.student.find({firstName: "Kido"}, { firstName: 1})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido" }
  • firstName, lastName 출력하기
> db.student.find({firstName: "Kido"}, { firstName: 1, lastName: 1})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae" }
  • 고정된 값으로 프로젝션 하기
-- 값을 채워서 출력 gender는 M으로 고정 
> db.student.find({firstName: "Kido"}, { firstName: 1, lastName: 1, gender: 'M'})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae", "gender" : "M" }

-- 값을 채워서 출력 gender는 F으로 고정 
> db.student.find({firstName: "Kido"}, { firstName: 1, lastName: 1, gender: 'F'})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae", "gender" : "F" }

-- 그냥 값 가져오려면 1로 세팅한다. 
> db.student.find({firstName: "Kido"}, { firstName: 1, lastName: 1, gender: 1})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido", "lastName" : "Bae", "gender" : "M" }

프로젝션에서 제외하기

  • 프로젝션에서 제외하고 싶다면 fieldName: 0 으로 세팅한다.
-- exclude 포함하고 싶지 않을때는 0을 세팅한다. 
> db.student.find({firstName: "Kido"}, { firstName: 0, lastName: 0, gender: 0})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "email" : "baekido@gmail.com", "country" : "Korea", "useYn" : false, "subject" : [ "maths", "english", "it" ], "totalScore" : 0 }

Update Document

  • 업데이트는 upate({검색조건}, {업데이트오퍼레이션: {업데이트값}}) 의 형식을 따른다.

단순 업데이트

  • 단순 업데이트를 위해서는 '$set' 오퍼레이션을 이용한다.
- 특정 id를 지정하여 해당 id의 firstName  값을 Kido2 로 변경한다 
> db.student.update({_id: ObjectId("6237c6a6c30fb6068b5cd258")}, { $set: {firstName: 'Kido2'}} )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find({ firstName: "Kido2"}, {firstName: 1, lastName: 1, gender: 1}).pretty()
{
        "_id" : ObjectId("6237c6a6c30fb6068b5cd258"),
        "firstName" : "Kido2",
        "lastName" : "Bae",
        "gender" : "M"
}

숫자 증가 업데이트

  • 숫자 증가를 위해서는 '$inc' 오퍼레이션을 이용한다.
> db.student.find({}, {totalScore: 1}).pretty()
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd259"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25a"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25d"), "totalScore" : 0 }

- $inc 오퍼레이션으로 숫자 증가 

> db.student.update({_id: ObjectId("6237c6a6c30fb6068b5cd258")}, {$inc: {totalScore: 999}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find({}, {totalScore: 1}).pretty()  
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "totalScore" : 999 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd259"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25a"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25d"), "totalScore" : 0 }

- $inc로 이전 값에 더하여 숫자를 증가 시켰다. 

> db.student.update({_id: ObjectId("6237c6a6c30fb6068b5cd258")}, {$inc: {totalScore: 999}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find({}, {totalScore: 1}).pretty()
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "totalScore" : 1998 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd259"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25a"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c"), "totalScore" : 0 }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25d"), "totalScore" : 0 }

값 제거하기

  • 리스트 내용에서 특정 값을 제거하기 위해서는 '$pull' 오퍼레이션을 이용한다.
- pull 을 이용하면 목록에서 설정된 내역이 삭제된다. 
> db.student.update({_id: ObjectId("6237c6a6c30fb6068b5cd258") }, {$pull: {subject: 'it'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find({_id : ObjectId("6237c6a6c30fb6068b5cd258")})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido2", "lastName" : "Bae", "email" : "baekido@gmail.com", "gender" : "M", "country" : "Korea", "useYn" : false, "subject" : [ "maths", "english" ], "totalScore" : 1998, "totalSpetotalScore" : 999 }
  • 결과를 확인하면 subject 에서 it 항목이 제거되었음을 알 수 있다.

값 추가하기

  • 값을 이번에는 추가하자. 추가를 위해서는 '$push' 오퍼레이션을 이용한다.
-- push 를 이용하면 목록에 아이템을 추가한다. 
> db.student.update( {_id: ObjectId("6237c6a6c30fb6068b5cd258") }, {$push: {subject: 'data-science'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find({_id : ObjectId("6237c6a6c30fb6068b5cd258")})
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258"), "firstName" : "Kido2", "lastName" : "Bae", "email" : "baekido@gmail.com", "gender" : "M", "country" : "Korea", "useYn" : false, "subject" : [ "maths", "english", "data-science" ], "totalScore" : 1998, "totalSpetotalScore" : 999 }

  • 신규로 'data-science'가 추가 되었음을 알 수 있다.

Delete Document

  • 삭제를 위해서는 deleteOne({삭제쿼리}) 를 이용할 수 있다.
  • 복수개의 삭제는 deleteMany({삭제쿼리}) 를 이용할 수 있다.

단건 삭제

> db.student.find({}, {_id: 1}).pretty()
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd259") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25a") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25d") }

- ObjectId("6237c7e6c30fb6068b5cd25d") 삭제 
> db.student.deleteOne({_id: ObjectId("6237c7e6c30fb6068b5cd25d")})
{ "acknowledged" : true, "deletedCount" : 1 }

> db.student.find({}, {_id: 1}).pretty()
{ "_id" : ObjectId("6237c6a6c30fb6068b5cd258") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd259") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25a") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b") }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c") }

권장하지 않는 단건삭제

  • 아래 커맨드를 입력하면 데이터가 삭제된다. (맨 위에것 부터 삭제 -- 이렇게 삭제는 하지 않아야한다. 주의)
> db.student.deleteOne({})
{ "acknowledged" : true, "deletedCount" : 1 }

여러건 도큐먼트 삭제

  • 조건에 해당하는 데이터 여러개 삭제
> db.student.deleteMany({lastName: 'Bae'})
{ "acknowledged" : true, "deletedCount" : 2 }

> db.student.find({}, {_id: 1, lastName: 1})
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25b"), "lastName" : "Bae1" }
{ "_id" : ObjectId("6237c7e6c30fb6068b5cd25c"), "lastName" : "Moo" }

전체 document 삭제하기

  • deleteMany({}) 를 이용하면 전체 데이터를 제거한다.
> db.student.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 2 }

WrapUp

  • 지금까지 MongoShell을 이용하뎌 간단한 CRUD를 수행해 보았다.
  • 매우 기초적인 내용이지만, mongodb에 대한 기본은 익힐 수 있었다.
  • 더 자세한 정보를 확인하기 위해서 https://www.mongodb.com/blog/channel/quickstart 등을 찾아보자.
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함