MongoDB - CosmosDB APIs
MongoDB is a NoSQL document-oriented database that stores data in JSON-like format. It uses a flexible schema approach to store and manage data, making it an ideal choice for modern applications.
Syntax
The basic syntax to connect to MongoDB using CosmosDB APIs is as follows:
const { MongoClient } = require('mongodb');
// Connection URI
const uri = '';
const client = new MongoClient(uri, { useNewUrlParser: true });
// Connect to the MongoDB instance
client.connect((err) => {
if (err) {
console.error(`Error occured: ${err}`);
} else {
// Perform database operations here
const db = client.db("DatabaseName");
// ...
client.close();
}
});
Example
Here is an example of inserting data into a MongoDB collection using CosmosDB APIs:
const { MongoClient } = require('mongodb');
// Connection URI
const uri = '';
const client = new MongoClient(uri, { useNewUrlParser: true });
// Connect to the MongoDB instance
client.connect((err) => {
if (err) {
console.error(`Error occured: ${err}`);
} else {
const db = client.db("mydb");
const collection = db.collection("users");
// Insert a document
const document = { firstName: "John", lastName: "Doe" };
collection.insertOne(document, (err, result) => {
if (err) {
console.error(`Error inserting document: ${err}`);
} else {
console.log(`Document inserted: ${result.insertedId}`);
}
// Close the connection
client.close();
});
}
});
Output
The output of the above example would be:
Document inserted: 5f2b85c7fc7aed16e20f77d3
Explanation
The code example above connects to a MongoDB instance using a connection URI. Once connected, it inserts a document into a collection named users
. A document is a single instance of data in MongoDB, and is similar in structure to a JSON object.
The insertOne()
function inserts the document into the collection, and if successful, returns an object containing the ID of the inserted document.
Finally, the connection is closed using the close()
function.
Use
You can use MongoDB with CosmosDB APIs to store and manage data in a NoSQL, document-oriented database.
Important Points
- MongoDB is a NoSQL document-oriented database.
- It stores data in JSON-like format.
- MongoDB uses a flexible schema approach to store and manage data.
- The basic syntax to connect to MongoDB using CosmosDB APIs is to use a connection URI and the
MongoClient
object. - Use
insertOne()
function to insert a single document to a collection in MongoDB. - MongoDB is an ideal choice for modern applications due to its scalability and ease of use.
Summary
MongoDB is a popular NoSQL document-oriented database that allows applications to store and manage data in JSON-like format. It offers a flexible schema approach and is a good choice for modern applications. Using CosmosDB APIs, you can easily connect to a MongoDB instance and perform various database operations.