MongoDB crash course, basic understanding of document databases

MongoDB crash course, basic understanding of document databases

MongoDB is a document store, which is a type of NO-SQL databases, it stores documents in BSON (Binary JSON) format and the maximal allowed size of the document is 16 MB.

Unlike SQL databases, no explicit is expected to be provided for documents, However, documents within the same collection tend to have similar structure.

System Structure

To understand how MongoDB works and why it is different from SQL databases, we need to understand the general structure of the MongoDB instance.

Similar to SQL databases, each MongoDB instance can contain several Databases, the database may contain many Collections, and finally each collection is a group of Documents of a similar structure.

Each document is a json object which could have nested other nested objects, arrays or values, and every document has a unique identifier (_id), which could be assigned manually or generated automatically during the document creation, but it can not be modified after that.

Sample Data

Let us have a collection of concerts, which contain the following 2 documents.

{
    "_id": "EI-346",
    "name": "Rock Festival",
    "location": "Prague, Czech republic",
    "date": { year: 2020, month: 4, day: 15 },
    "performers": ["Metallica", "Megadeth"],
    "tickets": { "count": 2500, "price": 250 }
},
{
    "_id": "EI-298",
    "name": "Summer Festival",
    "location": "Paris, France",
    "date": { year: 2020, month: 7, day: 22 },
    "performers": ["Marshmallow", "DJ Snake"],
    "tickets": { "count": 3100, "price": 190 }
}

Insert Operation

To insert a new document[s] into a given collection, use insert method, which expects either a single json document or a list of json documents.

db.[CollectionName].insert({});

If _id is provided, then it should be unique, otherwise it will be generated automatically.

If the collection [CollectionName] does not exist, then it will be created upon the first insertion.

Example 1: inserting one document

db.concerts.insert({
    "_id": "EI-123",
    "location": "Vienna, Austria",
    "name": "Winter Festival",
    "date": { year: 2020, month: 12, day: 25 }
});

Example 2: inserting list of documents

db.concerts.insert([
    {
        "_id": "EI-765",
        "name": "Imagination Festival"
    },
    {
        "_id": "EI-239",
        "location": "Berlin, Germany",
        "name": "Museum of Senses",
    }
]);

It is visible that inserted documents do not have the exact same fields.

Instead of insert method, a db.[CollectionName].insertOne(), can be used to insert exactly one document, while db.[CollectionName].insertMany() is used to insert multiple documents at once.

Update Operation

Update operation modifies or replaces at most an existing documents, unless we provide an option {multi: true}.

db.[CollectionName].update({});

When the update parameter contains no update operators, the whole document is replaced, but when we provide only update operators, the document will be modified.

Here is a list of some possible update operators:

  1. $set: sets the value of a given field / fields
  2. $rename: renames a given field / fields
  3. $inc: increments the value of a given field / fields
  4. $mul: multiplies the value of a given field / fields
  5. $push: adds one item / items to the end of an array

Example 3: Replacing the document that has the "_id: EI-765"

db.concerts.update(
  {
    "_id": ObjectId("EI-765")
  },
  {
    "location": "Prague, Czech republic", 
    "name": "Imagination Festival",
    "date": { year: 2019, month: 10, day: 12 }
  });                   

Example 4: Updating all concerts that is happening in 2020

db.concerts.update(
  {
    "date.year": 2020
  },
  {
    $set: {"canceled": ture}
  },
  { multi: true });  

Here we used multi: true because we want to update all matching documents otherwise it would have updated only the first matching one.

Update with upsert:

There is a special option that can be provided to update { upsert: true }, when specified and no documents match the query, a new document will be inserted (update here will act as insert).

Example 5: Trying to update a document with the "_id: EI-244" and since we don't have this document in our dataset, a new document will be inserted because { upsert: true }.

db.concerts.update(
  {
    "_id": ObjectId("EI-244")
  },
  {
    "location": "Dubai, UAE", 
    "name": "Union Day",
  },
  { upsert:: true });

Remove Operation

Removes matching documents from a given collection, unless { justOne: true } is provided

db.[CollectionName].remove({});

Example 6: Remove the document with "_id: EI-244"

db.concerts.remove(
  {
    "_id": ObjectId("EI-244")
  });

Find Operation

Retrieve a set of documents that match a provided query.

db.[CollectionName].find({});

Example 7: Get all concerts

db.concerts.find({});

Example 8: Get the concert with "_id: EI-123"

db.concerts.find({"_id": ObjectId("EI-123")});

Example 9: Get all concerts that will happen in 2020

db.concerts.find({"date.year": 2020});

Example 10: Get all concerts that will happen in 2020 or in Berlin, Germany

db.concerts.find({ 
  $or: [
      {"date.year": 2020}, 
      {"location": "Berlin, Germany"}
  ]
 });       

Example 11: Get all concerts sorted by month DESC

db.concerts.find({}).sort({"date.month": -1});

Note: 1 means ASC, -1 means DESC

Example 12: Get only location for the concert with the name "Summer Festival"

db.concerts.find({ "name: "Summer Festival" }, { "location": 1 });

Note: Here we are using a featured called projection, only the fields specified with 1, will be returned, except "_id", it will always will be returned.

To exclude the "_id", we provide "_id": -1

Example 13: Get all fields except date for the concerts that will happen in Prague, Czech republic

db.concerts.find({ "location: "Prague, Czech republic" }, { "date": -1 });

Note: Here projection is used to exclude the fields, all fields specified with -1, will not be returned.

Of Course MongoDB has more features, I tried to give here a quick introduction to the basic CRUD operation, and I hope this was helpful.

要查看或添加评论,请登录

Mahran Omairy的更多文章

  • Gulpjs: watch and livereload

    Gulpjs: watch and livereload

    In the previous article, we talked about gulpjs and we managed to create a couple of gulp tasks. we agree that to…

  • Gulpjs: automate your web development workflow

    Gulpjs: automate your web development workflow

    By definition Gulpjs is a task automating tool when it comes to web development and it runs on different platforms…

社区洞察

其他会员也浏览了