Basic MongoDB commands

Posted under » MongoDB on 7 Jan 2024

From mongosh, some familiar syntax.

test » show dbs
anodb 49 kb
test » use anodb
switched to db anodb
anodb » show collections
users
anodb » exit
$

You will notice that despite after deleting anodb you are still in the anodb. You can still create a table or collections for anodb at that point. Even if you have exited, you can still `use' anodb to add contents if it empty or edit if it already has contents.

To display database, you need to insert at least one document into it, otherwise it will not show the `show dbs' command.

Let's recreate the users `collection' which is like a table.

anodb» db.users.insertOne({ name : "Lee" })
{
  acknowledged: true,
  insertedId: ObjectId('6599d4d595e20b6405c31ca9')
}

The opposite of insertOne is to deleteOne.

Suppose you want to rename a field

You will see that the `id' index is created automatically. You will also notice that I didn't define any columns or schema yet it created the record or object or `document' automatically.

mth> db.students.updateOne({}, {$rename:{"name":"username"}}, false, true)
mth> db.students.updateMany({}, {$rename:{"old1":"new1", "old2":"new2"}}, false, true)

At this point, you will notice that MongoDB is very flexible and less rigid than MySQL. You can rename, recreate and shape your database as you go along. No longer are you stuck with a schema.

Now lets add another object.

db.users.insert({ name: "Shanmugam Pun", url: "http://www.kufar.com", tags: ['pap', 'dek', 'cow'], likes: 100})

As long as your JSON is correctly formatted, ie. numbers etc. you are able to insert. You can add array (tag eg.), because this is JSON you can also nest your input.

db.users.insert({ name: "Masagoes", 
comments: [{ user:"osama", message: "brown nose", dateCreated: new Date(2023,11,10,2,35) }]
})

Please note that is possible to insert duplicates if the col is not indexed.

Next we update the document.

anodb» db.users.updateOne({'name':'Masagoes'},{$set:{'likes':50}})

To show the 3 documents

anodb» db.users.find()
anodb» db.users.find({'name':'Masagoes'})

» basic query

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data