Escriu per cercar…

MongoDB

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 llegint una vista prèvia.

Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.

Inicia sessió