MongoDb
MongoDB is a document database, which means it stores data in JSON-like documents.
Official Websitehttps://www.mongodb.com
TagsDatabaseNoSQL
- JavaScript
- Python
Documentationhttp://mongodb.github.io/node-mongodb-native/
NodeJS packagehttps://www.npmjs.com/package/mongodb
Version5.9.2
Documentationhttps://pymongo.readthedocs.io/en/stable/
Pypi packagehttps://pypi.org/project/pymongo/
Version4.6.1
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.
Credential configuration
To configure this credential, you need the url
, username
and password
to connect to mongo.
Optionally, you can set any of the extra config parameters you can see here.
Here is an example of a filled credential configuration form in YepCode:
Mongodb Snippets available in Editor
note
The title is the triggering text for YepCode to autocomplete the script.
- JavaScript
- Python
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)
}
});
Integration
New integration from credential
mongodb_client = yepcode.integration.mongodb('credential-slug')
New integration from plain authentication data
from pymongo import MongoClient
mongodb_client = MongoClient(
"mongodb://yourhost:27017/",
username="username",
password="password",
tls=False,
)
Insert a Document
Insert a document
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
document = {
"name": "John",
"age": 30,
"city": "New York"
}
collection.insert_one(document)
Insert Multiple Documents
Insert multiple documents
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
documents = [
{"name": "John", "age": 30},
{"name": "Jane", "age": 25},
{"name": "Alex", "age": 35},
]
result = collection.insert_many(documents)
print(result.inserted_ids)
Find a Document
Find a document
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
query = {"name": "John"}
result = collection.find_one(query)
print(result)
Find Multiple Documents
Find multiple documents
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
query = {"age": {"$gt": 25}}
docs = collection.find(query)
for doc in docs:
print(doc)
Update a Single Document
Update a single document
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
filter_query = {"name": "John"}
update_query = {"$set": {"age": 32}}
collection.update_one(filter_query, update_query)
Update Multiple Documents
Update multiple documents
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
filter_query = {"age": {"$eq": 30}}
update_query = {"$inc": {"age": 5}}
result = collection.update_many(filter_query, update_query)
print("Modified %d documents", result.modified_count)
Delete One Document
Delete one document
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
query = {"name": "John"}
collection.delete_one(query)
Delete Multiple Documents
Delete multiple documents
db = mongodb_client["your_database_name"]
collection = db["your_collection_name"]
query = {"age": {"$gt": 30}}
result = collection.delete_many(query)
print("Deleted %d documents", result.modified_count)