CRUD operations
This is a cheat sheet of basic MongoDB CRUD operations.
We are going to use a collection which has the following form:
{ "country" : "United Kindgom", "city" : "London", "population" : "62,348,447", "languages" : [ "English", "Urdu", "Arabic" ] } { "country":"United States", "city" : "Washington", "population" : "310,232,863", "languages" : [ "English", "Spanish", "Arabic" ] }
Create
Create a database called world:
use world
Create a collection called population in the world database:
use world db.createCollection("population")
Insert a document into the collection population:
db.population.insert({ "country":"United Kindgom", "city" : "London", "population" : "62,348,447", "languages" : [ "English", "Urdu", "Arabic"] })
Read
Find all documents in the database:
db.collection.find()
Output:
{"_id" : ObjectId("52f10dd59ce0b0c798ef4f33"), "country" : "United Kindgom", "city" : "London", "population" : "62,348,447", "languages" : ["English","Urdu","Arabic"]}
Make the output readable:
db.collection.find().pretty()
Output:
{ "_id" : ObjectId("52f10dd59ce0b0c798ef4f33"), "country" : "United Kindgom", "city" : "London", "population" : "62,348,447", "languages" : [ "English", "Urdu", "Arabic" ] }
Find all documents where the city is London:
db.population.find({ city : "London" }).pretty()
Output:
{ "country" : "United Kindgom", "city" : "London", "population" : "62,348,447", "languages" : [ "English", "Urdu", "Arabic" ] }
Find all documents where the languages is Spanish:
db.population.find( { languages: { $in: [ "Spanish" ] } } )
Output:
{ "country":"United States", "city" : "Washington", "population" : "310,232,863", "languages" : [ "English", "Spanish", "Arabic" ] }
Update
Leave a Reply