1
const operations = [
    {
        updateOne: {
            filter: { email: 'email.1@gmail.com' },
            update: {
                firstName: 'firstName.1',
                lastName: 'lastName.1',
                password: 'Password',
            },
            upsert: true,
        },
    },
    {
        updateOne: {
            filter: { email: 'email.2@gmail.com' },
            update: {
                firstName: 'firstName.2',
                lastName: 'lastName.2',
                password: 'Password',
            },
            upsert: true,
        },
    },
    {
        updateOne: {
            filter: { email: 'email.3@gmail.com' },
            update: {
                firstName: 'firstName.3',
                lastName: 'lastName.3',
                password: 'Password',
            },
            upsert: true,
        },
    },
];

I have above operations that I want to perform inside bulkWrite operation.

try {
    const bulkWriteRes = await users.bulkWrite(operations);
    console.log(bulkWriteRes);
} catch (err) {
    console.log(err);
}

But inside bulkWriteRes I;m getting only these details.

BulkWriteResult {
    ok: 1,
    writeErrors: [],
    writeConcernErrors: [],
    insertedIds: [],
    nInserted: 0,
    nUpserted: 1,
    nMatched: 3,
    nModified: 3,
    nRemoved: 0,
    upserted: [
        {
            index: 5,
            _id: '63c977188eb489a9c9cfa4e2',
        },
    ],
};

I want whole updated object whether it is created or update including filed _id, fields that I have passed in filter and update properties. Is there any options ?

1 Answers1

0

You can put all your updates as individual documents and store them as a new collection first(says toBeUsers). Then, you can perform a $merge to upsert the records into users collection.

db.toBeUsers.aggregate([
  {
    "$merge": {
      "into": "users",
      "on": "email",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
])

Mongo Playground

ray
  • 11,310
  • 7
  • 18
  • 42