MongoDB is a document-oriented NoSQL database that offers high performance, high availability and easy scalability. He works with the concept of Collections and Documents. Collections are equivalent to tables in relational databases, while Documents are equivalent to rows. However, the structure of a Document is more flexible than that of a line, as each Document can have its own structure.
8.4. Inserting documents into MongoDB
To start working with MongoDB, it is important to understand the structure of its documents. In MongoDB, documents are structured in a format called BSON, which is a binary representation of JSON. Each document is made up of pairs of fields and values.
An example of a MongoDB document could be:
{ "_id": ObjectId("5099803df3f4948bd2f98391"), "name": "John", "age": 25, "profession": "Software Engineer" }
Fields in a document are like columns in a relational database table. The value can be several different types, including another document, an array of documents, and an array of values. The "_id" field is a special field that is automatically added by MongoDB to each document if you don't provide one. It must be unique for each document in a collection.
To insert a document into a collection, we use the "insertOne()" method if we want to insert a single document, or "insertMany()" if we want to insert multiple documents at once. Here is an example of how to insert a document:
db.collection('usuarios').insertOne({ name: "John", age: 25, profession: "Software Engineer" })
If the operation is successful, MongoDB returns an object that includes the operation status and the "_id" of the inserted document.
To insert multiple documents, we can pass an array of documents to the "insertMany()" method. Here is an example:
db.collection('usuarios').insertMany([ { name: "Maria", age: 30, profession: "Designer" }, { name: "Peter", age: 20, profession: "Student" } ])
If the operation is successful, MongoDB returns an object that includes the status of the operation and the "_id"s of the inserted documents.
Documents in MongoDB are very flexible. They do not need to have the same structure, which means that different documents in the same collection can have different sets of fields. This is one of the big advantages of MongoDB over relational databases, as it allows you to store data that is structurally diverse.
For example, a document in our "users" collection may have an additional "hobbies" field, while another document does not:
{ "_id": ObjectId("5099803df3f4948bd2f98392"), "name": "Ana", "age": 27, "profession": "Systems Analyst", "hobbies": ["Reading", "Cinema", "Running"] }
This flexibility makes MongoDB an excellent choice for dealing with semi-structured and unstructured data.
In summary, inserting documents into MongoDB is a simple and straightforward operation. The flexible document structure makes MongoDB a powerful tool for handling a wide variety of data.