• 회원가입
  • 로그인
  • 구글아이디로 로그인

[mongodb] Node.js - MongoDB Insert (데이터 입력)

4,059  
목차
  1. Collection에 데이터 입력
  2. Collection에 document 1개 입력
  3. Collection에 document 여러 개 입력
  4. result 객체
  5. _id 필드 - 고유 색인번호 지정해 데이터 입력

 

Collection에 데이터 입력

 

MongoDB에서 호출 되는 레코드 또는 문서를 컬렉션에 삽입하려면 insertOne() 메서드 사용.

 


 
1.
MongoDB의 document(문서)는 MySQL의 recode(레코드)와 동일.
 
2.
insertOne() 메소드의 첫 번째 매개변수는 삽입하려는 문서에 있는 각 필드의 이름과 값을 포함하는 객체임. 또한 오류 또는 삽입 결과로 작업할 수있는 콜백함수를 사용.

 

 

Collection에 document 1개 입력

1. C:\User\사용자명\hz.js 생성.

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

const options = {useUnifiedTopology: true};


MongoClient.connect(url, options, function(err, db) {

  if (err) throw err;

  var dbo = db.db("hz");

  var myobj = { mb_name: "homzzang", mb_level: "10" };

  dbo.collection("hz_member").insertOne(myobj, function(err, res) {

    if (err) throw err;

    console.log("1 document inserted");

    db.close();

  });

});

 


2. CMD 모드 창에서, 아래 명령어 실행.

 

C:\User\사용자명>node hz.js

 


[결과값]  

1 document inserted

 

 
참고 : 존재 않는 컬렉션에 document 삽입하려 할 경우, MongoDB가 컬렉션을 자동으로 생성.
 

Collection에 document 여러 개 입력

1. C:\User\사용자명\hz.js 생성.

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

const options = {useUnifiedTopology: true};


MongoClient.connect(url, options, function(err, db) {

  if (err) throw err;

  var dbo = db.db("hz");

  var myobj = [

    { mb_name: 'AAA', mb_level: '1'},

    { mb_name: 'BBB', mb_level: '2'},

    { mb_name: 'CCC', mb_level: '2'},

    { mb_name: 'DDD', mb_level: '3'},

    { mb_name: 'EEE', mb_level: '3'},

    { mb_name: 'FFF', mb_level: '3'},

    { mb_name: 'GGG', mb_level: '4'},

    { mb_name: 'HHH', mb_level: '4'},

    { mb_name: 'III', mb_level: '4'},

    { mb_name: 'JJJ', mb_level: '4'},

    { mb_name: 'KKK', mb_level: '5'},

    { mb_name: 'LLL', mb_level: '5'},

    { mb_name: 'MMM', mb_level: '5'},

    { mb_name: 'NNN', mb_level: '5'}

  ];

  dbo.collection("hz_member").insertMany(myobj, function(err, res) {

    if (err) throw err;

    console.log("Number of documents inserted: " + res.insertedCount);

    db.close();

  });

});

 


2. CMD 모드 창에서, 아래 명령어 실행.

 

C:\User\사용자명>node hz.js

 


[결과값]  

Number of documents inserted: 14

 

 

result 객체

 

1.

insertMany() 메서드 실행하면 result 객체가 반환됨.

result 객체 : 쿼리가 테이블에 미치는 영향 정보 내장.

 

2. 

result 객체 안의 각 속성의 속성값 접근 방법

result.property 

(예)res.insertedCount (삽입된 개수)

 

3.

콘솔에 출력하려면 JS함수 반환문 안에 아래 명령어 입력.

console.log(result.property)

(예) console.log(result.insertedCount)

주의: console.log()는 JS 명령어라, CMD 모드에 바로 입력 불가. 

 


※ 위 예제 경우, result 객체에 아래 정보 내장. 

※ console.log(res); 명령어로 확인 가능.

 

{

  result: { ok: 1, n: 14 },

  ops: [

    { mb_name: 'AAA', mb_level: '1', _id: 5f69a101dd216c03b8e71364 },

    { mb_name: 'BBB', mb_level: '2', _id: 5f69a101dd216c03b8e71365 },

    { mb_name: 'CCC', mb_level: '2', _id: 5f69a101dd216c03b8e71366 },

    { mb_name: 'DDD', mb_level: '3', _id: 5f69a101dd216c03b8e71367 },

    { mb_name: 'EEE', mb_level: '3', _id: 5f69a101dd216c03b8e71368 },

    { mb_name: 'FFF', mb_level: '3', _id: 5f69a101dd216c03b8e71369 },

    { mb_name: 'GGG', mb_level: '4', _id: 5f69a101dd216c03b8e7136a },

    { mb_name: 'HHH', mb_level: '4', _id: 5f69a101dd216c03b8e7136b },

    { mb_name: 'III', mb_level: '4', _id: 5f69a101dd216c03b8e7136c },

    { mb_name: 'JJJ', mb_level: '4', _id: 5f69a101dd216c03b8e7136d },

    { mb_name: 'KKK', mb_level: '5', _id: 5f69a101dd216c03b8e7136e },

    { mb_name: 'LLL', mb_level: '5', _id: 5f69a101dd216c03b8e7136f },

    { mb_name: 'MMM', mb_level: '5', _id: 5f69a101dd216c03b8e71370 },

    { mb_name: 'NNN', mb_level: '5', _id: 5f69a101dd216c03b8e71371 }

  ],

  insertedCount: 14,

  insertedIds: {

    '0': 5f69a101dd216c03b8e71364,

    '1': 5f69a101dd216c03b8e71365,

    '2': 5f69a101dd216c03b8e71366,

    '3': 5f69a101dd216c03b8e71367,

    '4': 5f69a101dd216c03b8e71368,

    '5': 5f69a101dd216c03b8e71369,

    '6': 5f69a101dd216c03b8e7136a,

    '7': 5f69a101dd216c03b8e7136b,

    '8': 5f69a101dd216c03b8e7136c,

    '9': 5f69a101dd216c03b8e7136d,

    '10': 5f69a101dd216c03b8e7136e,

    '11': 5f69a101dd216c03b8e7136f,

    '12': 5f69a101dd216c03b8e71370,

    '13': 5f69a101dd216c03b8e71371

  }

 

 

_id 필드 - 고유 색인번호 지정해 데이터 입력

 

_id 필드 지정 안 하면 MongoDB가 필드 추가하고 각 문서에 고유한 ID 할당.

위 예제 경우, id필드 지정이 없어, MongoDB가 각 문서에 고유한 _id 할당함.


직접 지정 시, _id필드 값은 각 문서에 대해 고유하게 설정해야 함. 

 


1. C:\User\사용자명\hz.js 생성.

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://localhost:27017/";

const options = {useUnifiedTopology: true};

 

MongoClient.connect(url, options, function(err, db) {

  if (err) throw err;

  var dbo = db.db("hz");

  var myobj = [

    { _id: 101, mb_name: 'OOO'},

    { _id: 102, mb_name: 'PPP'},

    { _id: 103, mb_name: 'QQQ'}

  ];

  dbo.collection("hz_member").insertMany(myobj, function(err, res) {

    if (err) throw err;

    console.log(res);

    db.close();

  });

});

 


2. CMD 모드 창에서, 아래 명령어 실행.

 

C:\User\사용자명>node hz.js

 


[결과값]

 

{

  result: { ok: 1, n: 3 },

  ops: [

    { _id: 101, mb_name: 'OOO' },

    { _id: 102, mb_name: 'PPP' },

    { _id: 103, mb_name: 'QQQ' }

  ],

  insertedCount: 3,

  insertedIds: { '0': 101, '1': 102, '2': 103 }

}

 



분류 제목
mysql Node.js - MySQL Update (데이터 수정)
mysql Node.js - MySQL Limit (데이터 출력개수)
mysql Node.js - MySQL Join (테이블 결합)
mongodb Node.js - MongoDB 설치・연결
mongodb Node.js - MongoDB Create Database (DB 생성)
mongodb Node.js - MongoDB Create Collection (콜렉션 생성)
mongodb Node.js - MongoDB Insert (데이터 입력)
mongodb Node.js - MongoDB Find (데이터 찾기)
mongodb Node.js - MongoDB Query (검색 쿼리)
mongodb Node.js - MongoDB Sort (데이터 정렬)
mongodb Node.js - MongoDB Delete (데이터 삭제)
mongodb Node.js - MongoDB Drop Collection (콜렉션 삭제)
mongodb Node.js - MongoDB Update (데이터 수정)
mongodb Node.js - MongoDB Limit (데이터 출력개수)
mongodb Node.js - MongoDB Join (콜렉션 결합)
module Node.js - assert 모듈 - 표현식의 참거짓 평가.
module Node.js - buffer 모듈 - 바이너리 데이터 처리. (= 버퍼 모듈)
module Node.js - child_process 모듈 - 자식 프로세스 실행.
module Node.js - cluster 모듈 - 단일 노드 프로세스를 여러 프로세스로 분할.
module Node.js - crypto 모듈 - OpenSSL 암호화 기능을 처리. (= 크립토모듈)
2/4
목록
찾아주셔서 감사합니다. Since 2012