Skip to main content

MongoDb

MongoDB is a document database, which means it stores data in JSON-like documents.

Network Connection needs

This integration needs network access to the server where the service is running.

See the Network access page for details about how to achieve that.

Mongodb snippets available in YepCode editor#

note

The title is the triggering text for YepCode to autocomplete the script

Integration#

New integration from credential
const mongodbClient = yepcode.integration.mongodb('credential-slug')
New integration from plain authentication data
const { MongoClient } = require('mongodb')
const url = "mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";
const mongodbClient = new MongoClient(url, {  tls: true,  auth: {      username: 'username',      password: 'password'  }});

Connect to MongoDB#

Connect (async/await)
try {    await mongodbClient.connect()
    // Your code here} catch (error)  {    console.error('Error connecting to MongoDB')    console.error(error)} finally {    await mongodbClient.close();}
Connect (Promise)
mongodbClient.connect().then(() => {    // Your code here}).catch((error) => {    console.error('Error connecting to MongoDB')    console.error(error)    throw error}).finally(() => {    mongodbClient.close();})
Connect (callback)
mongodbClient.connect((error, client) => {    if (error) {        console.error(error)    } else {        // Your code here    }    mongodbClient.close()})
Close client
await mongodbClient.close()

Insert a document#

Insert a document (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
try {    const results = await userCollection.insertOne({        id: '1235',        name: 'John',        email: 'john@foo.bar',    }, {        forceServerObjectId: true    })    console.log(results.insertedCount);    console.log(results.insertedId);    console.log(results.ops[0]);} catch (error) {    console.error(error)    throw error};
Insert a document (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.insertOne({    id: '1235',    name: 'John',    email: 'john@foo.bar',}, {    forceServerObjectId: true}).then((result) => {    console.log(result.insertedCount);    console.log(result.insertedId);    console.log(result.ops[0]);}).catch((error) => {    console.error(error)    throw error})
Insert a document (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.insertOne({    id: '1235',    name: 'John',    email: 'john@foo.bar',}, {    forceServerObjectId: true}, (error, result) => {    if (error)  {        console.error(error)        throw error    } else {        console.log(result.insertedCount);        console.log(result.insertedId);        console.log(result.ops[0]);    }})

Insert multiple documents#

Insert multiple documents (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
try {    const results = await userCollection.insertMany([{        id: '1236',        name: 'John',        email: 'john@foo.bar',    }, {        id: '1237',        name: 'Andy',        email: 'andy@foo.bar',    }], {        forceServerObjectId: true    })    console.log(results.insertedCount);    console.log(results.insertedIds);    console.log(results.ops[0]);} catch (error) {    console.error(error)    throw error};
Insert multiple documents (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.insertMany([{        id: '1236',        name: 'John',        email: 'john@foo.bar',    }, {        id: '1237',        name: 'Andy',        email: 'andy@foo.bar',}], {    forceServerObjectId: true}).then((result) => {    console.log(result.insertedCount);    console.log(result.insertedId);    console.log(result.ops[0]);}).catch((error) => {    console.error(error)    throw error})
Insert multiple documents (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.insertMany([{    id: '1236',    name: 'John',    email: 'john@foo.bar',}, {    id: '1237',    name: 'Andy',    email: 'andy@foo.bar',}], {    forceServerObjectId: true}, (error, result) => {    if (error)  {        console.error(error)        throw error    } else {        console.log(result.insertedCount);        console.log(result.insertedId);        console.log(result.ops[0]);    }})

Find a document#

Find a document (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
try {    const results = await userCollection.findOne({        id: '1234'    }, {        projection: {            name: 1,            id: 1        }    })    console.log(results);} catch (error) {    console.error(error)    throw error};
Find a document (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.findOne({    id: '1234'}, {    projection: {        name: 1,        id: 1    }}).then((results) => {    console.log(results);    return results}).catch((error) => {    console.error(error)    throw error});
Find a document (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.findOne({    id: '1234'}, {    projection: {        name: 1,        id: 1    }}, (error, results) => {    if (error) {        console.error(error)    } else {        console.log(results)    }});

Find multiple documents#

Find multiple documents (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
const cursor = userCollection.find({    id: '1234'}, {    projection: {        name: 1,        id: 1    }});
try {    const rowsCount = await cursor.count();    if (rowsCount === 0) {        console.log("No documents found!");    }
    await cursor.forEach(console.log);} catch (error) {    console.error(error)    throw error}
Find multiple documents (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
try {    const cursor = userCollection.find({        id: '1234'    }, {        projection: {            name: 1,            id: 1        }    });
    const rowsCount = await cursor.count();    if (rowsCount === 0) {        console.log("No documents found!");    }    await cursor.forEach(console.log);} catch (error) {    console.error(error)    throw error}
Find multiple documents (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
const cursor = userCollection.find({    id: '1234'}, {    projection: {        name: 1,        id: 1    }});
cursor.count((error, count) => {    if (count === 0 ) {        console.log("No documents found!");    } else {        cursor.forEach(console.log, (error) => {            console.error('An error instance during the execution.')            console.error(error)        });    }})

Update a single document#

Update a single document (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
try {    const results = await userCollection.updateOne({        id: '1234'    }, {        name: 'New name'    }, {        upsert: true    });    console.log(results)} catch (error) {    console.error(error)    throw error}
Update a single document (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.updateOne({    id: '1234'}, {    name: 'New name'}, {    upsert: true}).then((results) => {    console.log(results)}).catch((error) => {    console.error(error)    throw error})
Update a single document (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.updateOne({    id: '1234'}, {    name: 'New name'}, {    upsert: true}, (error, results) => {    if (error) {        console.error(error)    } else {        console.log(results)    }});

Update multiple documents#

Update multiple documents (async/await)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
try {    const results = await productCollection.updateMany({        stock: { $eq: 0 }    }, {        soldOut: true    });    console.log(results)} catch (error) {    console.error(error)    throw error}
Update multiple documents (Promise)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
productCollection.updateMany({    stock: { $eq: 0 }}, {    soldOut: true}).then((results) => {    console.log(results)}).catch((error) => {    console.error(error)    throw error})
Update multiple documents (callback)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
productCollection.updateMany({    stock: { $eq: 0 }}, {    soldOut: true}, {    upsert: true}, (error, results) => {    if (error) {        console.error(error)    } else {        console.log(results)    }});

Delete one document#

Delete one document (async/await)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');try {    const result = await userCollection.deleteOne({        id: '1234'    })    console.log(result.result)    console.log(`Deleted ${result.deletedCount} documents`)} catch (error) {    console.error(error)    throw error}
Delete one document (Promise)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.deleteOne({    id: '1234'}).then((result) => {    console.log(result.result)    console.log(`Deleted ${result.deletedCount} documents`)}).catch((error) => {    console.error(error)    throw error});
Delete one document (callback)
const databaseDB = mongodbClient.db('database');const userCollection = databaseDB.collection('user');
userCollection.deleteOne({    id: '1234'}, (error, result) => {    if (error) {        console.error(error)    } else {        console.log(result.result)        console.log(`Deleted ${result.deletedCount} documents`)    }});

Delete multiple documents#

Delete multiple documents (async/await)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
try {    const results = await productCollection.deleteMany({        soldOut: true    });    console.log(results)} catch (error) {    console.error(error)    throw error}
Delete multiple documents (Promise)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
productCollection.deleteMany({    soldOut: true}).then((results) => {    console.log(results)}).catch((error) => {    console.error(error)    throw error})
Delete multiple documents (callback)
const databaseDB = mongodbClient.db('database');const productCollection = databaseDB.collection('product');
productCollection.deleteMany({    soldOut: true}, (error, results) => {    if (error) {        console.error(error)    } else {        console.log(results)    }});