Junior — Middle
Можете объяснить, что такое MongoDB и как она работает как NoSQL база данных?
sobes.tech AI
Answer from AI
MongoDB is a document-oriented NoSQL database that stores data in BSON format (extended JSON). Unlike relational databases, MongoDB does not use tables and rows but works with collections of documents, which provides flexibility in data structure.
Main features of MongoDB:
- Flexible schema: documents in the same collection can have different structures.
- Scalability: supports horizontal scaling through sharding.
- High performance: due to indexes and built-in caching.
- Support for complex queries: aggregations, filtering, sorting.
In Go, the official driver go.mongodb.org/mongo-driver is commonly used for working with MongoDB. Example of connecting and inserting a document:
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
func main() {
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
collection := client.Database("testdb").Collection("users")
user := bson.D{{"name", "Ivan"}, {"age", 30}}
_, err = collection.InsertOne(context.TODO(), user)
if err != nil {
log.Fatal(err)
}
}
Thus, MongoDB is suitable for applications with dynamic data structures and requires high scalability.