MongoDB InsertData

From mi-linux
Jump to navigationJump to search

Main Page >> MongoDB >>MongoDB Workbook >> Insert Data

Inserting data

The format for the INSERT command is:

 db.collectionName.insert( 
  {
    key_1: 'value1',
    key_n: valueN
  }
 )

Note:

  • character and date values must be enclosed in matching single (') or double quotes (").
  • numeric values do not need quotes.
  • key/value pairs are comma-separated (no comma needed after the last pair)
  • each record is enclosed in curly brackets: {}

Department 10

The following example will create a dept collection that will represent the DEPT table seen in the Oracle Sample Data.

Add department 10:

db.dept.insert( 
 {
    deptno: 10, 
    dname: 'ACCOUNTING',
    loc: 'NEW YORK'
   } 
 )

Assuming you have no error messages, the system should respond with:

 WriteResult({ "nInserted" : 1 })

Department 20

Next add department 20:

db.dept.insert( 
 {
  deptno: 20,
  dname: 'RESEARCH',
  loc: 'DALLAS'
 }
)

Department 40

Next department 40:

db.deptCollection.insert( 
 {
   deptno: 40,
   dname: 'OPERATIONS',
   loc: 'BOSTON'
 }
)

Things to note

If you are getting errors, check carefully that:

  • every opening bracket has an appropriate closing bracket:
    • the insert statement uses round brackets: ()
    • an array uses square brackets: []
    • a collection uses curly brackets: {}
      • each element in a nested collection will also use curly brackets
  • each key:value pair are separated by commas, except for the last item
  • strings are enclosed in single or double quotes, e.g., 'myString', or "myString"
  • date strings are enclosed in single/double quotes and the format is 'yyyy-mm-dd' e.g., Date('2016-10-10')
  • use the Date() constructor to create a date datatype
  • date can also be a datetime, e.g., new Date("<yyyy-mm-ddThh:mm:ss>")
  • new Date() will return the current date

Exercise 2.1

  • Compare how you added the above data and how it differs from INSERT records in a relational database
  • Try and add Department 30. Note it has some values for the comm field.

Next Step

Querying the collection