> show dbs
> use [Database name]
> db
> db.dropDatabase()
> use [Database name]
> show collections
> db.createCollection('myCollection')
> db.myCollection.drop()
> db.COLLECTION_NAME.insert(document)
> db.myCollection.insert({
... ... 'name': 'Rwitesh',
... ... 'lang': 'Java',
... ... 'id': 1
... ... })
WriteResult({ "nInserted" : 1 })
Here myCollection
is the name of the collection.
[NOTE] You can use
db.myCollection.insertOne(document)
, if you want to add only one document.
> db.COLLECTION_NAME.insertMany([Store documents as array objects])
Here geeks
is a collection in which I have stored documents.
> db.geeks.insertMany([
... {
... First_Name : "Rwitesh",
... Last_Name : "Bera",
... Phone : "9876543210",
... id : 1
... },
... {
... First_Name : "Alistair",
... Last_Name : "Hey",
... Phone : "9080706050",
... id : 2
... },
... {
... First_Name : "Alex",
... Last_Name : "Ciro",
... Phone : "9192939495",
... id : 3
... }
... ])
> db.COLLECTION_NAME.find()
> db.geeks.find()
{ "_id" : ObjectId("6100483bb398f4a34021554b"), "First_Name" : "Rwitesh", "Last_Name" : "Bera", "Phone" : "9876543210", "id" : 1 }
{ "_id" : ObjectId("6100483bb398f4a34021554c"), "First_Name" : "Alistair", "Last_Name" : "Hey", "Phone" : "9080706050", "id" : 2 }
{ "_id" : ObjectId("6100483bb398f4a34021554d"), "First_Name" : "Alex", "Last_Name" : "Ciro", "Phone" : "9192939495", "id" : 3 }
> db.COLLECTION_NAME.find().pretty()
> db.geeks.find({"id" : 1})
{ "_id" : ObjectId("6100483bb398f4a34021554b"), "First_Name" : "Rwitesh", "Last_Name" : "Bera", "Phone" : "9876543210", "id" : 1 }
> db.geeks.count()
3
> db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
It will delete the document which has the given criteria.
> db.geeks.remove({"First_Name" : "Rwitesh"})
WriteResult({ "nRemoved" : 1 })
If you don't specify any criteria, then MongoDB will delete the entire documents from the collection.
> db.geeks.remove({})
Limit method accepts one number argument, which is the number of documents you want to be displayed.
> db.COLLECTION_NAME.find().limit(NUMBER)
Skip method accepts one number argument and is used to skip the number of documents.
> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Sort method is used to display documents in sorting order. Make sure that your each document has one key value.
> db.COLLECTION_NAME.find().sort({KEY:1})
> db.COLLECTION_NAME.find().sort({KEY:-1})
> db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Updating the id here
> db.geeks.update({"First_Name" : "Rwitesh"},
... {
... "First_Name" : "Rwitesh",
... "Last_Name" : "Bera",
... "Phone" : "9876543210",
... "id" : 999
... })