Insert Document
Command Purpose:
db.friendsCollection.insertOne({...})
it is used to insert a single document into thefriendsCollection
. IffriendsCollection
doesn't exist, MongoDB will create it automatically when you insert the first document.Document Structure: The document being inserted is enclosed in curly braces
{...}
. It represents a single record or entry in thefriendsCollection
. This document is similar to a row in a relational database table but can have a complex, nested structure.Field-Value Pairs: Inside the document, data is stored as field-value pairs. For example,
"firstname": "Monica"
means there's a field namedfirstname
with the value"Monica"
. Fields are similar to column names in a relational database, and values can be various data types (e.g., string, number, array, object).Data Types: MongoDB supports various data types. In this command,
firstname
,lastname
,location
, andprofession
are strings andage
is a number.Collection: A collection is similar to a table in a relational database. It's a grouping of documents, usually with related information. In this case,
friendsCollection
might hold documents for each friend, including their name, age, location, and profession.Database: The
db
part refers to the database you're working with. Databases contain collections, and a MongoDB server can host multiple databases.Read and Write Operations: After inserting data, you can retrieve, update, or delete it using MongoDB's CRUD (Create, Read, Update, Delete) operations. For example, you could use
db.friendsCollection.findOne({firstname: "Monica"})
to find Monica's document.Flexibility: MongoDB's schema-less nature means documents in the same collection don't need the same fields.
Globally Unique: The first 9 bytes (timestamp, machine identifier, and process ID) indeed contribute to the global uniqueness of the ObjectId.
Automatic Indexing: By default, MongoDB automatically creates a unique index on the _id
field for every collection, which helps in efficiently querying documents by their _id
.
Hexadecimal Representation The ObjectId is displayed as 24 hexadecimal characters when represented as a string. This is because each byte (8 bits) of the ObjectId is represented as two hexadecimal characters (each hex digit represents 4 bits). The conversion to hexadecimal doubles the apparent length of the ObjectId when viewed as a string. BSON
Binary encoded JSON
Widely used to transmit and store data across web apps. JSON is human-readable.
BSON is encoded, making it easier for machines to read.
MongoDB stores data in BSON format both internally and over the network.
Advantages of BSON
Efficient
Rich Data Types
Field Indexing
How BSON is stored in the MongoDB Database
insertMany() is used to insert more than one document.
Index
MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index.
Last updated