다음을 통해 공유


insert

insert 명령은 컬렉션에 새 문서를 만드는 데 사용됩니다. 단일 문서 또는 여러 문서를 한 번의 이동으로 삽입할 수 있습니다.

문법

insert 명령의 기본 구문은 다음과 같습니다.

db.collection.insert(
   <single document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

매개 변수

매개 변수 Description
<single document or array of documents> 컬렉션에 삽입할 문서 또는 문서 배열
writeConcern (선택 사항) 쓰기 문제를 나타내는 문서입니다. 쓰기 문제는 쓰기 작업을 위해 서버에서 요청한 승인 수준을 설명합니다.
ordered (선택 사항) 이 경우 true서버는 제공된 순서대로 문서를 삽입합니다. 이 경우 false서버는 순서에 관계없이 문서를 삽입할 수 있으며 오류에 관계없이 모든 문서를 삽입하려고 시도합니다.
  • <single document or array of documents>: 컬렉션에 삽입할 문서 또는 문서 배열입니다.
  • writeConcern:선택적. 쓰기 문제를 나타내는 문서입니다. 쓰기 문제는 쓰기 작업을 위해 서버에서 요청한 승인 수준을 설명합니다.
  • ordered:선택적. 이 경우 true서버는 제공된 순서대로 문서를 삽입합니다. 이 경우 false서버는 순서에 관계없이 문서를 삽입할 수 있으며 오류에 관계없이 모든 문서를 삽입하려고 시도합니다.

예제(들)

단일 문서 삽입

다음 명령은 StoreData 데이터베이스의 store 컬렉션에 단일 문서를 삽입합니다.

db.stores.insertOne({
  "storeId": "12345",
  "name": "Boulder Innovations",
  "location": {
    "lat": 37.7749,
    "lon": -122.4194
  },
  "staff": {
    "totalStaff": {
      "fullTime": 15,
      "partTime": 10
    }
  },
  "sales": {
    "totalSales": 500000.00,
    "salesByCategory": [
      {
        "categoryName": "Laptops",
        "totalSales": 300000.00
      },
      {
        "categoryName": "Smartphones",
        "totalSales": 200000.00
      }
    ]
  },
  "promotionEvents": [
    {
      "eventName": "Summer Sale",
      "promotionalDates": {
        "startDate": "2024-06-01",
        "endDate": "2024-06-30"
      },
      "discounts": [
        {
          "categoryName": "Laptops",
          "discountPercentage": 15
        },
        {
          "categoryName": "Smartphones",
          "discountPercentage": 10
        }
      ]
    },
    {
      "eventName": "Holiday Specials",
      "promotionalDates": {
        "startDate": "2024-12-01",
        "endDate": "2024-12-31"
      },
      "discounts": [
        {
          "categoryName": "Laptops",
          "discountPercentage": 20
        },
        {
          "categoryName": "Smartphones",
          "discountPercentage": 25
        }
      ]
    }
  ]
})

여러 문서 삽입

다음 명령은 저장소 컬렉션에 문서 배열을 삽입합니다.

db.stores.insertMany([
  {
    "storeId": "12346",
    "name": "Graphic Design Institute",
    "location": {
      "lat": 34.0522,
      "lon": -118.2437
    },
    "staff": {
      "totalStaff": {
        "fullTime": 20,
        "partTime": 5
      }
    },
    "sales": {
      "totalSales": 750000.00,
      "salesByCategory": [
        {
          "categoryName": "Laptops",
          "totalSales": 400000.00
        },
        {
          "categoryName": "Smartphones",
          "totalSales": 350000.00
        }
      ]
    },
    "promotionEvents": [
      {
        "eventName": "Black Friday",
        "promotionalDates": {
          "startDate": "2024-11-25",
          "endDate": "2024-11-30"
        },
        "discounts": [
          {
            "categoryName": "Laptops",
            "discountPercentage": 25
          },
          {
            "categoryName": "Smartphones",
            "discountPercentage": 30
          }
        ]
      }
    ]
  },
  {
    "storeId": "12347",
    "name": "Relecloud",
    "location": {
      "lat": 40.7128,
      "lon": -74.0060
    },
    "staff": {
      "totalStaff": {
        "fullTime": 10,
        "partTime": 20
      }
    },
    "sales": {
      "totalSales": 600000.00,
      "salesByCategory": [
        {
          "categoryName": "Laptops",
          "totalSales": 350000.00
        },
        {
          "categoryName": "Smartphones",
          "totalSales": 250000.00
        }
      ]
    },
    "promotionEvents": [
      {
        "eventName": "New Year Sale",
        "promotionalDates": {
          "startDate": "2024-01-01",
          "endDate": "2024-01-07"
        },
        "discounts": [
          {
            "categoryName": "Laptops",
            "discountPercentage": 10
          },
          {
            "categoryName": "Smartphones",
            "discountPercentage": 15
          }
        ]
      }
    ]
  }
])

_id 필드의 값 지정

_id 필드를 지정하지 않으면 서버에서 문서에 대한 고유한 ObjectId() 값을 자동으로 생성합니다. 문서에서 _id 필드를 지정하는 경우 컬렉션 내의 모든 문서에서 전역적으로 고유한 값이어야 합니다.

_id 필드에 대한 중복 값을 지정하면 서버에서 중복 키 위반 오류가 throw됩니다.

{
    "WriteErrors": [
        {
            "WriteError": {
                "err": {
                    "index": 0,
                    "code": 11000,
                    "errmsg": "Duplicate key violation on the requested collection: Index '_id_'",
                    "errInfo": "undefined",
                    "op": {
                        "testField": "testValue",
                        "_id": "1"
                    }
                }
            }
        }
    ]
}

여러 문서 순서대로 삽입

대량으로 삽입되는 문서는 "ordered"를 지정할 때 순서대로 삽입할 수 있습니다. true

db.stores.insertMany([
  {
    "_id": "123456",
    "storeId": "123456",
    "name": "Graphic Design Institute",
    "location": {
      "lat": 34.0522,
      "lon": -118.2437
    },
    "staff": {
      "totalStaff": {
        "fullTime": 20,
        "partTime": 5
      }
    },
    "sales": {
      "totalSales": 750000.00,
      "salesByCategory": [
        {
          "categoryName": "Laptops",
          "totalSales": 400000.00
        },
        {
          "categoryName": "Smartphones",
          "totalSales": 350000.00
        }
      ]
    },
    "promotionEvents": [
      {
        "eventName": "Black Friday",
        "promotionalDates": {
          "startDate": "2024-11-25",
          "endDate": "2024-11-30"
        },
        "discounts": [
          {
            "categoryName": "Laptops",
            "discountPercentage": 25
          },
          {
            "categoryName": "Smartphones",
            "discountPercentage": 30
          }
        ]
      }
    ]
  },
  {
    "_id": "234567",
    "storeId": "234567",
    "name": "Relecloud",
    "location": {
      "lat": 40.7128,
      "lon": -74.0060
    },
    "staff": {
      "totalStaff": {
        "fullTime": 10,
        "partTime": 20
      }
    },
    "sales": {
      "totalSales": 600000.00,
      "salesByCategory": [
        {
          "categoryName": "Laptops",
          "totalSales": 350000.00
        },
        {
          "categoryName": "Smartphones",
          "totalSales": 250000.00
        }
      ]
    },
    "promotionEvents": [
      {
        "eventName": "New Year Sale",
        "promotionalDates": {
          "startDate": "2024-01-01",
          "endDate": "2024-01-07"
        },
        "discounts": [
          {
            "categoryName": "Laptops",
            "discountPercentage": 10
          },
          {
            "categoryName": "Smartphones",
            "discountPercentage": 15
          }
        ]
      }
    ]
  }
], "ordered": true)

순서가 지정된 삽입 명령은 문서가 삽입된 순서를 확인하는 응답을 반환합니다.

{
    "acknowledged": true,
    "insertedIds": {
        "0": "123456",
        "1": "234567"
    }
}