Update document with conditions


I’m looking for a way to perform an update that adds/modifies the parameter “isShared” to true and if the queried document has no trasactionId parameter it adds this parameter too (with a mongoId). But if it exists, does not add it nor update it.

Chat gpt proposed something but it requires two trips to the DB, which is not optim, i think.

In other words: How can I convert the following code into another that avoids a previous check on the DB


const MongoClient = require('mongodb').MongoClient;

const { ObjectId } = require('mongodb');

const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";

const client = new MongoClient(uri, { useNewUrlParser: true });

async function shareDocument(documentId) {

  try {

    await client.connect();

    const collection = client.db("test").collection("documents");

    // check if the "transactionId" parameter exists

    const document = await collection.findOne({ _id: ObjectId(documentId), transactionId: { $exists: false } });

    if (!document) {

      // if the "transactionId" parameter exists, update the "isShared" parameter only

      await collection.updateOne({ _id: ObjectId(documentId) }, { $set: { isShared: true } });

    } else {

      // if the "transactionId" parameter does not exist, create it and update the "isShared" parameter

      await collection.findOneAndUpdate({ _id: ObjectId(documentId) }, { $set: { isShared: true, transactionId: new ObjectId() } });


  } catch (err) {


  } finally {

    await client.close();