Manage a document in Azure Cosmos DB for MongoDB using JavaScript

APPLIES TO: MongoDB

Manage your MongoDB documents with the ability to insert, update, and delete documents.

Note

The example code snippets are available on GitHub as a JavaScript project.

API for MongoDB reference documentation | MongoDB Package (npm)

Insert a document

Insert a document, defined with a JSON schema, into your collection.

// get database client for database 
// if database or collection doesn't exist, it is created
// when the doc is inserted

// insert doc
const doc = { name: `product-${random}` };
const insertOneResult = await client.db("adventureworks").collection("products").insertOne(doc);
console.log(`Insert 1 - ${JSON.stringify(insertOneResult)}`);

// insert docs
const docs = [
    { name: `product-${random}` },
    { name: `product-${random}` }
];
const insertManyResult = await client.db("adventureworks").collection("products").insertMany(docs);
console.log(`Insert many ${JSON.stringify(insertManyResult)}`);

The preceding code snippet displays the following example console output:

Insert 1 - {"acknowledged":true,"insertedId":"62b2394be4042705f00fd790"}
Insert many {"acknowledged":true,"insertedCount":2,"insertedIds":{"0":"62b2394be4042705f00fd791","1":"62b2394be4042705f00fd792"}}
done

Document ID

If you don't provide an ID, _id, for your document, one is created for you as a BSON object. The value of the provided ID is accessed with the ObjectId method.

Use the ID to query for documents:

const query = { _id: ObjectId("62b1f43a9446918500c875c5")};

Update a document

To update a document, specify the query used to find the document along with a set of properties of the document that should be updated. You can choose to upsert the document, which inserts the document if it doesn't already exist.

const product = {
    category: "gear-surf-surfboards",
    name: "Yamba Surfboard 3",
    quantity: 15,
    sale: true
};

const query = { name: product.name};
const update = { $set: product };
const options = {upsert: true, new: true};

const upsertResult = await client.db("adventureworks").collection('products').updateOne(query, update, options);

console.log(`Upsert result:\t\n${Object.keys(upsertResult).map(key => `\t${key}: ${upsertResult[key]}\n`)}`);

The preceding code snippet displays the following example console output for an insert:

Upsert result:
        acknowledged: true
,       modifiedCount: 0
,       upsertedId: 62b1f492ff69395b30a03169
,       upsertedCount: 1
,       matchedCount: 0

done

The preceding code snippet displays the following example console output for an update:

Upsert result:
        acknowledged: true
,       modifiedCount: 1
,       upsertedId: null
,       upsertedCount: 0
,       matchedCount: 1

done

Bulk updates to a collection

You can perform several operations at once with the bulkWrite operation. Learn more about how to optimize bulk writes for Azure Cosmos DB.

The following bulk operations are available:

const doc1 = {
  category: "gear-surf-surfboards",
  name: "Yamba Surfboard 3",
  quantity: 15,
  sale: true
};
const doc2={
  category: "gear-surf-surfboards",
  name: "Yamba Surfboard 7",
  quantity: 5,
  sale: true
};


// update docs with new property/value
const addNewProperty = {
  filter: { "category": "gear-surf-surfboards" },
  update: { $set: { discontinued: true } },
  upsert: true,
};


// bulkWrite only supports insertOne, updateOne, updateMany, deleteOne, deleteMany
const upsertResult = await client.db("adventureworks").collection('products').bulkWrite([
  { insertOne: {document: doc1}},
  { insertOne: {document: doc2}},
  { updateMany: addNewProperty},
  ]);

console.log(`${JSON.stringify(upsertResult)}`);

The preceding code snippet displays the following example console output:

{
  "ok":1,
  "writeErrors":[],
  "writeConcernErrors":[],
  "insertedIds":[
    {"index":0,"_id":"62b23a371a09ed6441e5ee30"},
    {"index":1,"_id":"62b23a371a09ed6441e5ee31"}],
  "nInserted":2,
  "nUpserted":0,
  "nMatched":10,
  "nModified":10,
  "nRemoved":0,
  "upserted":[]
}
done

Delete a document

To delete documents, use a query to define how the documents are found.

const product = {
    _id: ObjectId("62b1f43a9446918500c875c5"),
    category: "gear-surf-surfboards",
    name: "Yamba Surfboard 3",
    quantity: 15,
    sale: true
};

const query = { name: product.name};

// delete 1 with query for unique document
const delete1Result = await client.db("adventureworks").collection('products').deleteOne(query);
console.log(`Delete 1 result:\t\n${Object.keys(delete1Result).map(key => `\t${key}: ${delete1Result[key]}\n`)}`);

// delete all with empty query {}
const deleteAllResult = await client.db("adventureworks").collection('products').deleteMany({});
console.log(`Delete all result:\t\n${Object.keys(deleteAllResult).map(key => `\t${key}: ${deleteAllResult[key]}\n`)}`);

The preceding code snippet displays the following example console output:

Delete 1 result:
        acknowledged: true
,       deletedCount: 1

Delete all result:
        acknowledged: true
,       deletedCount: 27

done

See also