7 minutes read

In MongoDB, we can assume documents are the data to be collected in the databases. The documents can be numbers (1,2,3,4,5), letters (a, b, c, d, e), Boolean expressions (true/false), arrays [apple, mango, banana], symbols (@, #, !); anything depending on the users' needs. The collections, on the other hand, are groupings of those data.

Representation of the database

To get a proper understanding of what the collections of documents are, let's take the bookshelf above as an example. Books are like documents. Each book has its own set of fields that describe it: the author, its title, and so on. The shelves they are on can be considered collections. Just like there are shelves of books, there are collections of documents in MongoDB.

Collections

A grouping of documents (Data) is called a Collection in MongoDB. These collections can store different kinds of documents. The documents can have similar or different fields, as the user prefers. However, similar is better because the relayed information or the objective of the collection may be unclear to other people besides the one who created the database.

Documents and collections comparison

In the collection, each and all documents are independent of each other. Also, in a database containing several collections, each collection is independent of the other. It means that if the information contained inside a collection of a database is tampered with or is updated, the other information contained inside is not affected. With this comes the concept of MongoDB being schemaless.

Schemaless

Firstly, we should know what schema is. Schema means a structured framework or a plan. For MongoDB to be schemaless means that in every document we insert into the collection, one document doesn't need to be similar to another or have the same fields. Each document is independent, one document can have more fields than the other. They are not bounded by a certain framework.

{
 "_id" : ObjectId("62bc53bcae5478e5e03ffec7"),
 "name" : "Harry",
 "class" : 9, 
 "grade" : "A"
},
{
 "_id" : ObjectId("62bc5557ae5478e5e03ffec8"),
 "name" : "Sam", 
 "class" : 9,
 "grade" : "B", 
 "gender" : "Male" 
},
{
 "_id" : ObjectId("62bc5557ae5478e5e03ffec9"),
 "name" : "Smith", 
 "class" : 10,
 "grade" : "C",
 "gender" : "Female"
}

As you can see in the example above, each document is independent of another or is different compared to others, having more or fewer fields. This is what it means to not be bounded by schemas.

There’s freedom in inserting the information for each field in the documents. Each and all documents inside the collection are unique and independent. Tampering with any document does not affect the other documents inside the collection. It is the same for the collections within a database. If any of the documents inside the collection is updated, the updated collection does not affect other collections in the database.

Schemas provide specific rules that you must follow when entering the data into the database. But sometimes flexibility of data is needed. If one document requires more information than the other, having no schemas proves to be beneficial.

Inserting documents in collections

There are several ways we can insert the documents into the collection.

To insert one document into only one collection in MongoDB you should do the following:

db.NameOfCollection.insertOne()
db.shelf.insertOne({"title": "Alice in Wonderland","author": "Lewis Carrol"}) 
 

Here, the document is enclosed by curly braces {}. Inside the document, there are certain fields. These fields can be of several data types according to the users' needs, be they letters, numbers, or symbols. Fields are separated by commas.

After successfully inserting the document into the collection, you'll see the following:

{
  "acknowledged" : true,
  "insertedId" : ObjectId("63444faf40e18a784d787f88")
} 

This indicates that the document was added to the collection.

Later on, while using MongoDB, you might need to insert several documents at once. So, here's what you should do in such cases:

db.NameOfCollection.insertMany([])
db.shelf.insertMany([{"title": "Judge and Prejudice", "author": "Jane Austen"},
                     {"title": "The Alchemist", "author": "Paulo Coelo"},
                     {"title": "Anna Karenina", "author": "Leo Tolstoy"}]) 
        

If the documents were successfully added to the collection, you will see the following:

{
  "acknowledged" : true,
    "inserted Ids" : [ 
       ObjectId("62db131bf74e35daf0c941ef"), 
       ObjectId("62db131bf74e35daf0c941f0"),
       ObjectId("62db131bf74e35daf0c941f1") 
    ]
}

Here the object Ids are given to each document, making them unique.

Just like when we inserted a single piece of data, each document is separated by curly braces {} followed by a comma. They are enclosed within the big braces [].

Now that we have inserted the documents into the collection, we need to view them.

Viewing the documents

After inserting the documents into the collection, the collection has to be viewed to see what documents were inserted. To view the files you should use the following code:

db.NameOFCollection.find()

In the above syntax, db means Database and NameOfCollection is the name that the user has entered to use as the name of the collection. The name can be anything the user wants it to be. The name "shelf" is used in the example below. Lastly, the function find() views the collections.

db.shelf.find()

The output will be the following:

{ "_id" : ObjectId("62db1195f74e35daf0c941ee"), "title" : "Alice in Wonderland", "author" : "Lewis Carrol" }
{ "_id" : ObjectId("62db131bf74e35daf0c941ef"), "title" : "Judge and Prejudice", "author" : "Jane Austen" }
{ "_id" : ObjectId("62db131bf74e35daf0c941f0"), "title" : "The Alchemist", "author" : "Paulo Coelo" }
{ "_id" : ObjectId("62db131bf74e35daf0c941f1"), "title" : "Anna Karenina", "author" : "Leo Tolstoy" }

The problem with this one is that the fields are not correctly oriented and can be confusing at times. So, to solve this problem, we can use the pretty() function which helps properly orient the data and view them.

db.NameOFCollection.find().pretty()

db.shelf.find().pretty()

The output will be the following:

{
        "_id" : ObjectId("62db1195f74e35daf0c941ee"),
        "title" : "Alice in Wonderland",
        "author" : "Lewis Carrol"
}
{
        "_id" : ObjectId("62db131bf74e35daf0c941ef"),
        "title" : "Judge and Prejudice",
        "author" : "Jane Austen"
}
{
        "_id" : ObjectId("62db131bf74e35daf0c941f0"),
        "title" : "The Alchemist",
        "author" : "Paulo Coelo"
}
{
        "_id" : ObjectId("62db131bf74e35daf0c941f1"),
        "title" : "Anna Karenina",
        "author" : "Leo Tolstoy"
}

So, to understand properly, let's reiterate:

  • db = database.
  • NameOfCollection = the name of the collection the user has entered.
  • find() = the function that is used to view the documents.
  • pretty() = the function that is used to properly orient the documents.

Conclusion

In this topic, we’ve discussed the following points:

  • In MongoDB, a database is composed of documents and collections of documents.
  • Schemas of any kind do not bind fields inside documents.
  • You can insert either one or multiple documents depending on your needs.
  • Using the find() function, you can view a specific collection.
  • You can use the pretty() function after find() to properly arrange the result for easier readability.
12 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo