Escribe para buscar…

MongoDB

Esta página todavía no se ha traducido — se muestra en su idioma original:Català

Introducció

Entorn de treball

Arranca la base de dades:

ps
start-process -NoNewWindow mongod.exe

Crea un projecte amb Bun:

ps
mkdir monogdb
cd monogdb
bun init -y

Afegeix una dependència amb mongodb:

ps
bun add mongodb

Obre el projecte amb WebStorm.

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.

ts
// fish.ts
import {MongoClient} from "mongodb"

// MongoDB deployment's connection string
const uri = "mongodb://localhost:27017"

// Create a new client and connect to MongoDB
const 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()
}

Estás leyendo una vista previa.

Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.

Iniciar sesión