Inserting Data into Cosmos DB for MongoDB

One of the most basic operations is inserting data into a collection. In this guide, we will cover everything you need to know about inserting data using the Mongo Shell (Mongosh).

Inserting a Single Document

The most basic way to insert data into MongoDB is to insert a single document. To do this, you can use the db.collection.insertOne() method. The insertOne() method takes a single document as its argument and inserts it into the specified collection. Here's an example of how you might use this method:

db.myCollection.insertOne({
  name: "John Smith",
  age: 30,
  address: "123 Main St"
});

In this example, we're inserting a document into the "myCollection" collection with the following fields: "name", "age", and "address". Once the command is executed, you will see the acknowledged: true and insertedId: ObjectId("5f5d5f5f5f5f5f5f5f5f5f5f") in the output, where the insertedId is the unique identifier generated by MongoDB for the inserted document.

Inserting Multiple Documents

In many cases, you'll need to insert multiple documents at once. To do this, you can use the db.collection.insertMany() method. The insertMany() method takes an array of documents as its argument and inserts them into the specified collection. Here's an example:

db.myCollection.insertMany([
  {name: "Jane Doe", age: 25, address: "456 Park Ave"},
  {name: "Bob Smith", age: 35, address: "789 Elm St"},
  {name: "Sally Johnson", age: 40, address: "111 Oak St"}
]);

In this example, we're inserting three documents into the "myCollection" collection. Each document has the same fields as the previous example: "name", "age", and "address". The insertMany() method returns an acknowledged: true and insertedIds: [ObjectId("5f5d5f5f5f5f5f5f5f5f5f5f"), ObjectId("5f5d5f5f5f5f5f5f5f5f5f5f"), ObjectId("5f5d5f5f5f5f5f5f5f5f5f5f")] where insertedIds is an array of unique identifiers generated by MongoDB for each inserted document.

Inserting with Options

Both insertOne() and insertMany() accept an optional second argument, which can be used to specify options for the insert operation. For example, to set the "ordered" option to false, you can use the following code:

db.myCollection.insertMany([
  {name: "Jane Doe", age: 25, address: "456 Park Ave"},
  {name: "Bob Smith", age: 35, address: "789 Elm St"},
  {name: "Sally Johnson", age: 40, address: "111 Oak St"}
], {ordered: false});

This tells MongoDB to insert the documents in an unordered fashion, meaning that if one document fails to be inserted, it will continue with the next one. This is recommended for write performance in Cosmos DB for MongoDB

Next steps