DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

Cover image for CRUD Operation in MongoDB
Ranjit Odedra
Ranjit Odedra

Posted on

CRUD Operation in MongoDB

Base Notes

table โ†’ collections

row โ†’ documents

column โ†’ fields

Base Commands

start mongodb โ†’ mongo

show dbs โ†’ to show data bases

use newdb โ†’ if db is not present then create it otherwise use it

db โ†’ give active database

Create

insertOne()

db.collectionname.insertOne({name:โ€ReactJSโ€,type:โ€frontendโ€,videos:80,active:true}) โ†’ it create colleection of collectionname and create document

insertMany()

db.collectionname.insertMany([{ name:โ€ReactJSโ€,type:โ€frontendโ€,videos:80,active:true},{name:โ€ReactJSโ€,type:โ€frontendโ€,videos:80,active:true}])show collections โ†’ gives all collections in dbdb.collectionname.find() โ†’ gives all documents of the collectionname

db.collectionname.find().pretty() โ†’ give documents of collectionname in a good format

Read

find()

db.collection.find({queary,projection}) โ†’ for read

db.collection.find({name:โ€physicsโ€},{_id:0,name:1}) โ†’ it will print name of having name as physics

limit()

db.collection.find({name:โ€physicsโ€},{_id:0,name:1}).limit(2)-> it will only print first 2

findOne() โ†’ gives on document

db.collection.findOne({name:โ€physicsโ€},{_id:0,name:1})

skip(1)โ†’ it will give from second one

db.collection.find({name:โ€physicsโ€},{_id:0,name:1}).limit(2).skip(1)

UPDATE

updateOne() โ‡’ db.collection.updateOne(,)

db.cone.updateOne({name:"Physics"},{$set:{value:300}}) โ†’ update value by 300 of doc having name Physics

updateMany() โ‡’ db.collection.updateMany(,)

db.cone.updateMany({name:"Physics"},{$set:{value:300}}) โ†’ update value by 300 of docs having name Physics

Delete

deleteMany(criteria)

db.cone.deleteMany({name:"Physics"}) โ†’ delete doc having name as Physics

db.cone.deleteMany({}) โ†’ delete all docs

Top comments (0)

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.