MongoDB

Attribute Types in MongoDB

The following article describes Attribute Types in MongoDB.

In particular, MongoDB, documents can have different types of attributes. To emphasize, the attributes in MongoDB belong to one of these types.

  1. Scalar Types. In effect, these attribute types allow a single value.
    • String: Represented as a UTF-8 string.
    • Integer: Represented as a 32-bit or 64-bit integer.
    • Double: Represented as a floating-point number.
    • Boolean: Represented as a true or false value.
    • Date: Represented as an ISO date string or as a BSON date type.
    • Null: Represented as a null value.
  2. Array Types. In contrast, arrays represent a collection of values.
    • Array: An ordered list of values of any data type, including other arrays.
  3. Embedded Documents. Meanwhile, a document can be a part of another document.
    • Document: A nested set of key-value pairs within a parent document.
  4. Special Types. However there are some special types.
    • Object ID: A unique identifier for each document, automatically generated by MongoDB.
    • Binary Data: Binary data can be stored in a MongoDB document as a BSON binary type.
    • Decimal128: A 128-bit decimal value.

In addition, it is possible that the structure of a document can change dynamically. So, the user can store documents with different attributes in the same collection.

Attribute Types in MongoDB – Using Arrays

In order to use an array, we need to use square brackets, enclosing the values. For example, the following is an array in a MongoDB document.

{
    "_id": ObjectId("5f9d80f0efa12e085f5e5b5c"),
    "name": "John Doe",
    "email": "johndoe@example.com",
    "interests": ["reading", "traveling", "music"],
    "purchases": [
        {
            "product": "Book",
            "price": 19.99,
            "date": ISODate("2022-01-01T00:00:00.000Z")
        },
        {
            "product": "Airline Ticket",
            "price": 299.99,
            "date": ISODate("2022-06-01T00:00:00.000Z")
        }
    ]
}

Evidently, the interests field is an array of strings and the purchases field is an array of embedded documents. The embedded documents in the purchases array each have three fields: product, price, and date.

Useful Links

What is MERN Stack?

Features of MERN Stack

Alternatives of MERN Stack


Further Reading

Some Examples of MongoDB Documents

Overview of Mean Stack

Creating Single Page Applications with Angular

Angular 10 Data Binding in Different Ways

Creating Some Angular Components

Examples of Array Functions in PHP

Basic Programs in PHP

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *