Brogramo
Guest
Guest

What is a Document in MongoDB?

MongoDB documents

A document in MongoDB is a series of key-value pairs wrapped in curly braces.

MongoDB document example

{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"pet_name" : "Tom",
"pet_type" : "cat"
}

The structure of a MongoDB document follows JSON-like specification known as BSON.

Documents are grouped by collections in MongoDB, where each collection is equivalent to a table, and each document is equivalent to a row in a NoSQL database.

MongoDB subdocuments

A subdocument is a document within another document.

MongoDB subdocument example

{
"_id" : ObjectId("5c1d358bf383fbee028aea0b"),
"pet_name" : "Tom",
"pet_type" : "cat",
"pet_attributes": { // pet_attributes is a subdocument

    "favorite_toy": "string",
    "whisker_legth" "unknown"
    }
}

pet_attributes is a subdocument.

How to create a document in MongoDB

  • Use the insertOne() method to insert one document.
  • Use the insertMany() method to insert more than one document.

insertOne() creates one document

db.items.insertOne(
  { "_id" : 1, "item" : "ABC", "price" : 10, "quantity" : 2, "expires" : new Date("01-05-2022")}
);
// db.items is the items collection

// insertOne() inserts a document in the items collection

insertMany() creates multiple documents

db.items.insertMany([
  { "_id" : 1, "item" : "ABC", "price" : 10, "quantity" : 2, "expires" : new Date("01-05-2022")},
  { "_id" : 2, "item" : "ZEF", "price" : 2, "quantity" : 54, "expires" : new Date("11-04-2022")},
]);