You are on page 1of 2

MONGODB TUTORIAL

Create Operations
In mongodb the database is made using the use command

for example :- use shopdb

this command will create the database shopdb and will let us use it.

In this database we can create many tables which are called collections.

The insertOne() operation creates both the database myNewDB and the


collection myNewCollection1 if they do not already exist..
use myNewDB
db.myNewCollection1.insertOne( { x: 1 } )

db.createCollection(name, options)

Because MongoDB creates a collection implicitly when the collection is first referenced in a command,
this method is used primarily for creating new collections that use specific options.

db.products.insertOne( { _id: 10, item: "box", qty: 20 } );


This statement creates three columns id, item and qty in the table products
And inserts the respective values in the form of passing objects.

db.products.insertMany( [
{ _id: 10, item: "large box", qty: 20 },
{ _id: 11, item: "small box", qty: 55 },
{ _id: 12, item: "medium box", qty: 30 }
] )
In order to insert many records at a time we have to use the above code snippet.

READ OPERATIONS :-

db.bios.find( { "name.last": "Hopper" } )

The following operation returns documents in the bios collection where the field last in


the name embedded document equals "Hopper".

db.bios.find(
{ _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } }
)

The following operation uses the $in operator to return documents in the bios


collection where _id equals either 5 or ObjectId("507c35dd8fada716c89d0013"):

db.bios.find( { birth: { $gt: new Date('1950-01-01') } } )

The following operation uses the $gt operator returns all the documents from the bios collection
where birth is greater than new Date('1950-01-01'):

db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )

Combine comparison operators to specify ranges for a field. The following operation returns from
the bios collection documents where birth is between new Date('1940-01-01') and new
Date('1960-01-01') (exclusive):

db.bios.find( {
birth: { $gt: new Date('1920-01-01') },
death: { $exists: false }
} )

The following operation returns all the documents from the bios


collection where  birth  field is  greater than   new Date('1950-01-
01')  and  death  field does not exists:

The second parameter is used (projection) to tell us which fields are used to include in the
results of the queries.

You might also like