Skip to content

Instantly share code, notes, and snippets.

@bugcy013
Forked from blkpark/db_account.md
Last active October 5, 2015 09:33
Show Gist options
  • Select an option

  • Save bugcy013/5d6941bc506b69c20f02 to your computer and use it in GitHub Desktop.

Select an option

Save bugcy013/5d6941bc506b69c20f02 to your computer and use it in GitHub Desktop.
MongoDB Basics
  • mongo collection to csv export
mongoexport --host [hostname] --port [portNumber] --db [backupDBName] --collection [collectionName] --csv --fields field1,field2,field3,field4 --out [exportedFileName.csv]
  • dump
mongodump -o [outfileLocation] --db [dbName] --host [hos] --port [portNum]
  • dump file restore
mongorestore -d [사용할 db이름] --port 28017 [복구할 db폴더]
sudo service mongod --config /etc/mongod.conf
sudo service mongodb stop
sudo service mongodb restart
sudo service mongodb status
  • dump
//[전체 덤프]
mongodump --out ./mongoback_20150120.bson -uikoob -p

[DB지정]
mongodump --out ./mongoback_20150120.bson —db ucb -uikoob -p

User Management Methods

ref (http://docs.mongodb.org/manual/reference/method/js-user-management/)

User Create

/* 
* db.createUser()
*/

// products db에 nspark유저를 생성.
// admin db에  readAnyDatabase와 clusterAdmin role을 부여
// products db는 readWrite role을 부여
use products
db.createUser( { "user" : "nspark",
                 "pwd": "password string",
                 "customData" : { employeeId: 12345 },
                 "roles" : [ { role: "clusterAdmin", db: "admin" },
                             { role: "readAnyDatabase", db: "admin" },
                             "readWrite"
                             ] },
               { w: "majority" , wtimeout: 5000 } )
               
// products db에 dbAccount1유저를 생성하고 readWrite role을 부여              
use products
db.createUser(
   {
     user: "dbAccount1",
     pwd: "password",
     roles: [ "readWrite", "dbAdmin" ]
   }
)

// admin db에 role없이 reportsUser유저를 생성 
use admin
db.createUser(
   {
     user: "reportsUser",
     pwd: "password",
     roles: [ ]
   }
)

// admin db에 clusterAdmin role을 가진 appAdmin유저를 생성
// config db에 readWrite role을 생성
use admin
db.createUser(
   {
     user: "appAdmin",
     pwd: "password",
     roles:
       [
         { role: "readWrite", db: "config" },
         "clusterAdmin"
       ]
   }
)

Change User Password

db.changeUserPassword("reporting", "SOh3TbYhx8ypJPxmt1oOfL");

Role

// 사용자 정의 role 생성
// ____________________________________________________________________________
use admin
  
db.createRole({
    // 사용자 정의 role 이름
    role: "userRole1",
    // 권한 리스트
    privileges: [
        // product.inventory collection은 읽기/쓰기 가능 (삭제는 못함)
        {
            resource: {db: "product", collection: "inventory"},
            actions: ["find", "update", "insert"]
        },
        // product.orders collection은 read만 가능
        {
            resource: {db: "product", collection: "orders"},
            actions: ["find"]
        } 
    ],
    // built-in-roles에서 상속받고자 하는 role을 기입. 필수값이므로 없으면 빈 array라도 있어야 함.
    roles: []
})
  
  
// 생성된 권한을 특정 사용자에게 부여
// ____________________________________________________________________________
db.createUser({user: "user1", pwd: "1111", roles: ["userRole1"]})
  
  
// 권한이 부여된 사용자를 이용하여 테스트
// ____________________________________________________________________________
use product
 
// 성공
db.inventory.insert({no: 1, name: "product1"})
// 실패
db.orders.insert({no: 1, products: [1,2,3]})
  
// 성공
db.inventory.find()
// 성공
db.orders.find()
Person.find({occupation: /host/})
    .where('name.last')
    .equals('Ghost')
    .where('age')
    .gt(17).
    lt(66)
    .where('likes')
    .in(['vaporizing', 'talking'])
    .limit(10)
    .sort('-occupation')
    .select('name occupation')
    .exec(callback);
var Team = mongoose.Schema({
    teamName:       String,
    teamURL:        String,
    teamMembers:    [{username: String, password: String, email: String, dateCreated: Date}],
});

var Team = db.model('Team', Team);

Team.findOne({'teamMembers.username': 'Bioshox'}, {'teamMembers.$': 1},
    function (err, team) {
        if (team) {
            console.log(team.teamMembers[0].email);
        }
    }
);

(UPDATE VS SAVE) - (SAVE VS INSERT) function

  • UPDATE : 특정필드만 수정하기
  • SAVE :도큐먼트 덮어쓰기
    • 같은 _id가 있어도 오류를 발생시키지 않고 그 값을 수정
      • 필드가 6개 존재하고 2개를 SAVE할 경우 6개 필드가 다 사라지고 새로 저장하는 2개만 저장됨
  • INSERT : 같은 _id가 있으면 오류
  	db.service.insert(
  		{
			"name" : "gmap test",
			"regdate": new Date(),
			"desc" : "app name"
		}
	);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment