Tag Archives: check like select query

Create collection(table) and insert document(rows) in Mongodb

Create collection(table) and insert document(rows) in Mongodb

Create the table and insert data into the MongoDB. Following are the steps for MongoDB:

1. Check the db which is connected.

db

2. Connect with mydb database

use mydb

3. Create two documents named j and k by using the following sequence of javascript

j = {name:"RAM"}
k = {address:"delhi"}
i = {x:3}

4. Insert the  j, k and i into the collection name employee

db.employee.insert(j)
db.employee.insert(k)
db.employee.insert(i)

5. Check the collection exists

show collections

6. confirm the document insert into the collection

db.employee.find()

Example

-- Switch to the DB
> use mydb
switched to db mydb

-- Show all db present
> show dbs
admin  (empty)
local  0.078GB
test   (empty)

-- Assigned value
> j={name:"RAM"}
{ "name" : "RAM" }
> k={address:"Delhi"}
{ "address" : "Delhi" }
> i={empno:10}
{ "empno" : 10 }

-- Insert data into collection
> db.employee.insert(j)
WriteResult({ "nInserted" : 1 })
> db.employee.insert(k)
WriteResult({ "nInserted" : 1 })
> db.employee.insert(i)
WriteResult({ "nInserted" : 1 })

--Check collection present in DB
> show collections
employee
system.indexes

--Run Select query for fetch inserted data
> db.employee.find()
{ "_id" : ObjectId("540eb24efbf4b1a1447adde9"), "name" : "RAM" }
{ "_id" : ObjectId("540eb25ffbf4b1a1447addea"), "address" : "Delhi" }
{ "_id" : ObjectId("540eb267fbf4b1a1447addeb"), "empno" : 10 }

--Check databases
> show dbs
admin  (empty)
local  0.078GB
mydb   0.078GB
test   (empty)