Skip to content

MongoDB - Basic CRUD Operations

In MongoDB documents can be inserted to collections. Collections reside inside databases.

Setting Up

We need to first specify the database that we will be using. Let's switch to the database test:

MongoDB
use test

After that, let's create a document called users:

MongoDB
db.createCollection("users")

Built-In IDs

Each MongoDB document has a built-in ID. So whenever you insert a new document inside a collection, the document will always get an unique ID for itself.

For example, two documents stored in the cars collection could look like this:

[
  {
    _id: ObjectId("62aae293adec45e9cb477b3b"), // (1)!
    manufacturer: 'Ford',
    model: 'Mondeo'
  },
  {
    _id: ObjectId("62aae293adec45e9cb477b3b"), // (2)!
    manufacturer: 'Tesla',
    model: 'Model 3'
  },
],
  1. Automatically generated by MongoDB when the document was inserted.
  2. Automatically generated by MongoDB when the document was inserted.

Inserting Documents

To add one or many documents to MongoDB collection, the commands db.collection.insertOne() and db.collection.insertMany can be used.

For example:

MongoDB
db.users.insertOne({ username: "tester", password: "abc123", age: 19 })
MongoDB
db.users.insertMany([ { username: "test2", age: 21 }, { username: "test3" } ])

Note that the example above only contained text and number for the field data types. You can see also from the above that as MongoDB does not enforce any kind of schema by default, any kind of documents can also be stored inside collections.

For example:

MongoDB
db.users.insertOne({
  username: "test4",
  age: 22,
  hobbies: [ "skiing", "walking" ],
  address: {
    "street": "...",
    "zipcode": "..."
  }
})