Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ensure buildBulkWriteOperations target shard if shardKey is set #14621

Conversation

matlpriceshape
Copy link
Contributor

@matlpriceshape matlpriceshape commented May 30, 2024

Fixes #14622

Summary

When having a sharded collection and having set shardKey on the schema, using buildBulkWriteOperations does not take the shardKey into account.

The documention for shardKey states (https://mongoosejs.com/docs/guide.html#shardKey):

Each sharded collection is given a shard key which must be present in all insert/update operations

This PR enabled support for the shardKey option when using the buildBulkWriteOperations method.

Examples

Given this schema

const measurementSchema = new Schema({
  temperature: { type: Number },
  sensorId: { type: String },
}, { shardKey: { sensorId: 1 } });

const Measurement = db.model('Measurement',measurementSchema )

and assuming an saved document m, this bulkSave action will correctly include sensorId in the bulkWrite command:

m.temperature = 21.1

await Measurement.bulkWrite([m])
/* This will generate 

bulkWrite([
  {
    updateOne: {
      filter: {
        _id: ...,
        sensorId: 1
      },
      {
        update: {
          $set: {
            temperature: 21.1
          }
        }
      }
    },
  },
])

*/

@matlpriceshape matlpriceshape changed the title Make sure buildBulkWriteOperations target shard if shardKey is set fix: ensure buildBulkWriteOperations target shard if shardKey is set May 30, 2024
@matlpriceshape matlpriceshape marked this pull request as ready for review May 30, 2024 09:12
@vkarpov15 vkarpov15 added this to the 8.4.1 milestone May 30, 2024
@vkarpov15
Copy link
Collaborator

Thanks 👍

@vkarpov15 vkarpov15 merged commit 90f9e55 into Automattic:master May 30, 2024
23 of 24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Bulk operations not including shardKey
2 participants