MongoDB
Introducció
Section titled “Introducció”Entorn de treball
Section titled “Entorn de treball”Arranca la base de dades:
start-process -NoNewWindow mongod.exe
Crea un projecte amb Bun:
mkdir monogdbcd monogdbbun init -y
Afegeix una dependència amb mongodb
:
bun add mongodb
Obre el projecte amb WebStorm.
Inserir documents
Section titled “Inserir documents”You can insert a document into a collection using the collection.insertOne()
method. To insert a
document, define an object that contains the fields and values that you want to store. If the specified
collection does not exist, the insertOne()
method creates the collection.
Crea el fitxer fish.ts
A continuació, insereix un peix a la col·lecció fish
de la base de dades ocean
.
import {MongoClient} from "mongodb"
// MongoDB deployment's connection stringconst uri = "mongodb://localhost:27017"
// Create a new client and connect to MongoDBconst client = new MongoClient(uri)
try {
// Connect to the "ocean" database and access its "fish" collection const database = client.db('ocean') const fish = database.collection('fish')
// Delete all the fish from the collection await fish.deleteMany()
// Create a document to insert const sardine = { name: "sardine" }
// Insert the defined document into the "ocean" collection const result = await fish.insertOne(sardine)
// Print the ID of the inserted document console.log(`A document was inserted with the _id: ${result.insertedId}`)
} finally { // Close the MongoDB client connection await client.close()}
Executa l’script per inserir el peix:
bun fish.ts
L’script insereix el peix i mostra per consola la _id
del document que acabes d’inserir.
A document was inserted with the _id: 68037bb02d7454bf8c570b86
Crea un nou “Data Source” per treballar amb la base de dades:
Pots veure que s’ha creat un document a la col·lecció fish
:
Pots inserir diversos documents alhora utilitzant el mètode collection.insertMany()
:
import {MongoClient} from "mongodb"
const uri = "mongodb://localhost:27017"const client = new MongoClient(uri)
try {
const database = client.db('ocean') const fish = database.collection('fish')
await fish.deleteMany()
const sardine = { name: "sardine" }
await fish.insertOne(sardine)
await fish.insertMany([ {name: "tuna" }, {name: "cod" } ])
} finally { await client.close()}
Encontrar documentos
Section titled “Encontrar documentos”PENDIENTE REVISAR
Pots consultar un sol document d’una col·lecció amb el mètode collection.findOne()
. El mètode findOne()
utilitza un document de consulta que proporcioneu per coincidir només amb el subconjunt dels documents de la col·lecció que coincideixen amb la consulta. Si no proporcioneu un document de consulta o si proporcioneu un document buit, MongoDB coincideix amb tots els documents de la col·lecció.
L’operació findOne()
només retorna el primer document coincident
Exemple
Section titled “Exemple”El fragment següent troba un sol document de la col·lecció movies
. Utilitza els paràmetres següents:
-
Un document de consultaque configura la consulta per retornar només pel·lícules amb el títol exactament del text
'The Room'
. -
Un sort que organitza els documents coincidents en ordre descendent per puntuació, de manera que si la nostra consulta coincideix amb diversos documents, el document retornat serà el document amb la puntuació més alta.
-
Una projecció que exclou explícitament el camp
_id
dels documents retornats i que inclou explícitament només els campstitle
iimdb
de l’ objecte (i els seus camps incrustats).
import {MongoClient} from "mongodb"
const uri = "mongodb://localhost:27017"const client = new MongoClient(uri)
type Movie = { title: string year: number released: Date plot: string type: "movie" | "series" imdb: IMDB}
type IMDB = { rating: number votes: number id: number}
type MovieSummary = Pick<Movie, "title" | "imdb">
async function run(): Promise<void> { try { const database = client.db("sample_mflix") // Specifying a Schema is always optional, but it enables type hinting on // finds and inserts const movies = database.collection<Movie>("movies") const movie = await movies.findOne<MovieSummary>( {title: "The Room"}, { sort: {rating: -1}, projection: {_id: 0, title: 1, imdb: 1}, } ); console.log(movie) } finally { await client.close() }}
run().catch(console.dir)
Mira tots els exemples que hi ha en aquest enllaç: Usage Examples
Ves a la pantalla “Overview” del cluster, i veus a l’enllaç on posa “Connect” per obtenir la URI de connexió.
Pots veure que per connectar-te a la base de dades remota l’URI de connexió conté una contrasenya, i aquesta contrasenya no pot ser al codi per motius de seguretat.
Afegeix la llibreria dotenv
:
bun add dotenv
Crea el fitxer .env
al directori arrel del projecte, i afegeix la variable DB_CONN_STRING
:
DB_CONN_STRING="mongodb+srv://<username>:<password>@cluster.2hr0xbm.mongodb.net"
Modifica el fitxer .gitignore
perquè el fitxer .env
no es guardi a Git.
.env
Crea el script atlas.ts
El codi és el mateix que abans, excepte que ara la URI està en una variable d’entorn:
import {MongoClient} from "mongodb"import dotenv from 'dotenv'
dotenv.config()const uri = process.env.DB_CONN_STRING
const client = new MongoClient(uri!)
try {
const database = client.db('earth')
const fish = database.collection('birds') await fish.deleteMany()
await fish.insertOne({ name: "pigeon" })
await fish.insertMany([ {name: "partridge"}, {name: "nightingale"} ])
} finally { await client.close()}
El contingut d'aquest lloc web té llicència CC BY-NC-ND 4.0.
©2022-2025 xtec.dev