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)