Skip to content

Instantly share code, notes, and snippets.

@anmolsukki
Last active May 4, 2020 15:53
Show Gist options
  • Select an option

  • Save anmolsukki/8dab7a8ca972a4ab7cbd998966047aab to your computer and use it in GitHub Desktop.

Select an option

Save anmolsukki/8dab7a8ca972a4ab7cbd998966047aab to your computer and use it in GitHub Desktop.
MongoDB Basics

MongoDB Create Collections

insert Collections

db.collection_name.insert([{
    name : "Anmol",
    roll_no : 452,
    college : "SVIET",
    year : 2017,
    language : ["Android", "Reactjs", "MongoDB"]
}])

insertOne Collections

db.collection_name.insertOne({
    name : "Firoz",
    age : "24",
    friends : ["abc", "pqr", "xyz"]
})

insertMany Collections

db.collection_name.insertMany([
    { name: "Midhuna", age: 23, cars: [ "BMW 320d", "Audi R8" ], place:"Amaravati" },
    { name: "Akhil", age: 24, cars: [ "Audo A7", "Agera R" ], place:"New York", size: { h: 14, w: 21, uom: "cm" } },
    { name: "Honey", age: 25, cars: [ "Audi R8" ] }
])

Show Collections

show collections

MongoDB Delete Collection

db.collection_name.drop()

MongoDB find Collection

db.collection_name.find({})

or

db.collection_name.find({name:"Firoz"})

or

db.collection_name.find({}).pretty()

or

db.collection_name.find({}, {"place" : 1})

Find Specify Conditions (using more than 1 document condition)

Find "place" headers "A" and "D" condition document

db.collection_name.find( { place: { $in: [ "A", "D" ] } } )

Find less than value in Specific parameter Document: Using AND operator ("place" and "qty" is header_name)

db.collection_name.find( { place: "A", qty: { $lt: 30 } } )

Find matching parameter A and less than value both Specific parameter: Using OR operator

db.collection_name.find( { $or: [ { place: "A" }, { qty: { $lt: 80 } } ] } )

MongoDB Documents Count

db.collection_name.find({}).count()

Add New Column in collection

db.collection_name.update({}, {$set: {write_column_name:"value"}} , {multi: true});

Example

db.collection_name.update({}, {$set: {roll_no:1}} , {multi: true});

Update Document Header name

db.collection_name.updateMany( {}, { $rename: { "document_header_old": "document_header_new" } } )

MongoDB Delete Documents

Delete Multiple With Condition

db.collection_name.deleteMany({name: "Anmol"}, {age: 24})

Delete single item in Documents

db.collection_name.remove({name: "Anmol"}, {justOne: true})

Delete Whole Documents

db.collection_name.remove({})

Delete Whole Column

db.collection_name.update({}, {$unset: {column_name}} , {multi: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment