Node.js/DB

Node.js mongodb example

Soul-Learner 2015. 5. 28. 00:20

Node.js 가 지원하는 Mongodb 사용 예



테스트 환경

Windows 8.1

MongoDB, Mongoose, Node.js

Visual C++ 2012, Python 2.7



MongoDB 다운로드 및 설치

 - http://www.mongodb.org/downloads



MSI 파일이나 압축파일(zip) 다운로드 및 설치


설치 후 실행

 MongoDB를 실행하기 전에 데이터가 저장될 디렉토리를 생성해 놓고 실행시에 해당 디렉토리를 아규먼트로 전달해야 한다

 데이터 저장용 디렉토리를 지정하지 않고 mongod.exe를 실행하면 디폴트로 C:\data\db 폴더를 참조하여 없을 경우 오류발생

 콘솔을 이용하여 bin 디렉토리로 이동하여 mongod.exe 파일을 다음과 같이 실행한다

mongod --dbpath c:\mongodb\data<enter>


MongoDB Shell ( mongo.exe )


콘솔을 이용하여 bin 으로 이동하여 mongo<enter>

Microsoft Windows [Version 6.3.9600]

(c) 2013 Microsoft Corporation. All rights reserved.


C:\MongoDB\Server\3.0\bin>mongo

MongoDB shell version: 3.0.3

connecting to: test <-- mongo 를 실행할 때 데이터베이스 이름을 아규먼트로 전달하지 않으면 디폴트로 test 라는 데이터베이스와 연결된다

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

        http://docs.mongodb.org/

Questions? Try the support group

        http://groups.google.com/group/mongodb-user

>


위와같이 MongoDB Shell을 실행하면 디폴트 데이터베이스인 test를 대상으로 관리를 수행할 수 있다


Microsoft Windows [Version 6.3.9600]

(c) 2013 Microsoft Corporation. All rights reserved.


C:\MongoDB\Server\3.0\bin>mongo

MongoDB shell version: 3.0.3

connecting to: test

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

        http://docs.mongodb.org/

Questions? Try the support group

        http://groups.google.com/group/mongodb-user


> show  tables

system.indexes

users


> db.users.insert({_id:'usr01', name:"scott", phone:'010-4345-5433'})

WriteResult({ "nInserted" : 1 })


> db.users.insert({_id:'usr02', name:'smith', phone:'010-3333-5555'})

WriteResult({ "nInserted" : 1 })


> db.users.insert({_id:'usr03', name:'jone', phone:'010-4567-9876' })

WriteResult({ "nInserted" : 1 })


> db.users.find()

{ "_id" : "usr01", "name" : "scott", "phone" : "010-4345-5433" }

{ "_id" : "usr02", "name" : "smith", "phone" : "010-3333-5555" }

{ "_id" : "usr03", "name" : "jone", "phone" : "010-4567-9876" }

>


_id 와 같은 필드를 사용한 이유는 MongoDB 내부에서 _id 라는 필드를 프라이머리 키로 지정하여 사용하고 있는데 레코드를 입력할 때 _id 필드가 없으면 MongoDB는 _id 필드 아래에 임의의 값을 저장한다

그러므로 검색 등 관리를 좀더 편리하게 하기 위해서 _id 라는 필드에 값을 저장해주면 MongoDB는 그대로 받아 들이게 된다

_id 으로 지정된 필드의 값은 일단 입력된 후에는 변경할 수 없게 된다


자료형은 명시할 필요없고 컬럼의 수와 컬럼명도 레코드 입력시에 결정된다


다음과 같이 배열형태를 이용하면 batch insert도 가능하다

db.users.insert( [{},{}] )


GUI 관리툴(Robomongo) 다운로드 및 설치: http://robomongo.org/


Robomongo 실행 및 MongoDB에 연결

Robomongo를 실행하면 MongoDB Connections 설정창이 나타난다

최초실행시에는 아직 연결된 MongoDB가 없는 상태이므로 연결된 항목이 없는 리스트가 보여진다

MongoDB Connections 창에서 Create 링크를 누르고 다음과 같이 설정한 후 Test 버튼을 눌러 연결을 테스트한다

 - Name : 임의의 연결이름

 - Address : 서버주소, 여기서는 localhost

 - Port : 27017


연결 테스트에 성공하면 차후에는 이 연결을 자주 사용할 것이므로 Save 버튼을 눌러 설정을 저장한다


연결 리스트에서 설정된 이름을 선택하고 하단의 Connect 버튼을 누르면 설정된 MongoDB와 연결되고 연결설정창은 사라진다


연결설정창이 사라지면 Robomongo 메인 화면의 왼쪽 패널에는 연결이름과 그 아래에 데이터베이스 이름이 나열되어 있다

test 라는 데이터베이스 하위에 users 라는 테이블을 더블클릭하면 오른편에 지금까지 저장된 항목을 모두 볼 수 있다

users 테이블 위에서 마우스 우측을 누르고 insert Document 등의 항목을 선택하여 CRUD 작업이 가능하다


연결이름 위에서 마우스 우측을 누르고 Create Database를 선택하면 임의의 데이터베이스를 생성할 수 있고 그 데이터베이스 안에 Collection(Table)을 생성할 수도 있다


데이터베이스 관리는 mongo.exe Shell을 사용할 수도 있고, Robomongo 처럼 GUI 툴을 활용할 수도 있다


mongo.exe 를 콘솔에서 실행할 때 데이터베이스 이름을 지정하지 않으면 디폴트로 test 라는 데이터베이스와 연결된다.

mongo products 와 같이 실행하면 products 데이터베이스와 연결된다 이때 데이터베이스가 존재하지 않으면 새로 생성된다


db.users.insert({_id:'usr01', name:'scott'}) 을 Shell에서 사용하면 해당 테이블이 존재하지 않으면 자동으로 생성된다


Shell을 종료하려면 Ctrl + C 를 누르면 된다


Shell을 통해 입력된 데이터는 Robomongo 화면에서 확인된다. 또한 Robomongo 하면에서 작업한 내용은 mongo Shell 을 통해서도 확인할 수 있다


Batch Insert 예

db.users.insert( [

{ "_id" : "usr01", "name" : "scott", "phone" : "010-4345-5433", "age" : 20 },

{ "_id" : "usr02", "name" : "smith", "phone" : "010-3333-5555", "age" : 20 },

{ "_id" : "usr03", "name" : "jone", "phone" : "010-4567-9876" },

{ "_id" : "usr04", "name" : "ward", "phone" : "010-3455-6788", "age" : 30 }

])


테이블에서 데이터 가져오기

db.users.find() : 모든 행을 가져온다

db.users.find( {user_id:'usr01'} ) : 특정 아이디로 검색한 결과를 가져온다


구간검색을 위한 연산자( $gt, $lt, $gte, $lte ) 사용 예

http://docs.mongodb.org/manual/reference/operator/query/

db.users.find( { usr_num:{$gt:10}}, {user_id:0, name:1, usr_num:1 } } --> 필드가 1으로 설정된 필드만 출력

db.users.find( { usr_num:{ $gt:10,$lt:20 } }, {user_id:0, name:1, usr_num:1 } }


http://docs.mongodb.org/manual/reference/operator/

부정연산자 ($ne ) 사용예

db.users.find( { name: { $ne: 'king' } } )


http://docs.mongodb.org/manual/reference/operator/query/

논리연산자($or, $and, $not, $nor) 


검색결과 정렬(sort)

sort()를 사용하지 않으면 디폴트로 1(오름차순)으로 지정됨, -1(내림차순)

db.users.find().sort({age:-1})



데이터의 변경

db.users.update ( {name:'scott'}, {$set:{age:20}} )

변경하고자 하는 필드가 없는 레코드에도 적용되며 해당 필드가 없으면 새로 생성되어 지정된 값이 저장된다

변경하고자 하는 레코드가 없는 경우에는 레코드를 새로 생성하도록 옵션을 true 으로 설정할 수 있다

db.users.update ( {name:'king'}, {$set:{age:50}}, true)



데이터의 삭제

db.users.remove( {name:'king'} ) : 조건에 합치되는 행 삭제

db.users.remove( {age:{$lt:20} ) : 구간 삭제

db.users.remove( {} ) : 전체삭제


테이블 삭제

db.users.drop()


쉘에서 작업 중인 데이터베이스를 변경하려면 use otherdb<enter> 를 이용한다

윈도우에 서비스로 등록할 수 있는 명령도 있다


쉘명령으로 DB 생성법

db.createCollection("mydb");


db.mytb.findOne()

db.mytb.find().pretty()



Node.js 에서 MongoDB를 사용하는 방법

가장 널리 사용되는 방식은 Node.js의 mongo-native 드라이버 모듈을 사용하는 것이다

MongoDB를 설치할 때 Native 코드로 컴파일되어야 하므로 VC++ 2012 컴파일러와 Python 2.7 컴파일러가 필요하다


VC++ 컴파일러와 파이썬(2.7)이 필요함



Mongoose

Mongoose MongoDB ODM

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.

Mongoose 는 Node.js의 라이브러리(모듈)이며 MongoDB를 사용하면서 오브젝트 모델링을 위한 툴로 코드상에서 사용된다


우선 VS2012 설치

Python 2.7 설치


그 다음에 Mongoose 설치

Install : npm install mongoose

위와같이 설치하면 Native모듈로 컴파일되어 빌드된다

만약 설치과정에서 컴파일되지 않으면 node_gyp 툴을 사용하여 수동으로 컴파일해야 함


Mongoose CRUD example

/**

 * New node file

 */

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test'); // 포트번호(27017) 생략가능


var Schema = mongoose.Schema;

var ObjectId = Schema.ObjectId;


var userSchema= new Schema({

_id: String,

name: String,

phone: String,

age: Number }, { versionKey:false} /*__v 버전키 필드제거 */

);


//module.exports = mongoose.model('User', userSchema);

// 생성자함수 이므로 대문자 권장

var User = mongoose.model('Users', userSchema); // 'User 단수형를 이름은 내부적으로 복수형으로 사용됨


// Users 컬렉션에서 가져오기

User.find ( function (err, users) {

 if (err){ return console.error(err);}

 console.log(users);

});


/*

 //Users 컬렉션에 저장할 모델 인스턴스 생성

var newUser = new User({

_id:'usr03', name:'ward', phone:'010-658-3646', age:30

});


// 모델 인스턴스의 속성을 Users 컬렉션에 저장

newUser.save(function(err, newUser){

if (err) { return console.error(err); }

 console.log(newUser);

}); */


/*

//Find a single User by name.

User.findOne({ name: 'ward' }, function(err, scott) {

  if (err) { return console.error(err); }

  console.log(scott);

}); */


/*

// Update 1

User.update( {_id:'usr01'}, {$set:{name:'king'}}, {upsert:true}, function(err, doc){

if(err) { return console.error('Failed to update'); }

console.log('Update Success');

});

*/


/*

// findOneAndUpdate

User.findOneAndUpdate ( {_id:'usr03'}, {$set:{name:'king', age:50} }, {upsert:true}, function(err, doc){

if(err) { return console.error('Failed to update'); }

console.log('Update Success');

}); */


/*

// 삭제

User.findByIdAndRemove('usr03', function(err){

if(err) { return console.error(err); }

console.log('Remove Success');

});*/