CSFLE with data key per document


I would like to implement Client-Side Field Level Encryption where each document (e.g. user) would be encrypted with its data key. This feature was mentioned keynote in 2019 on Field Level Encryption in MongoDB 4.2 (MongoDB World 2019 Keynote, part 4) - YouTube.

Until now I have managed to set up “per collection encryption” with defining $jsonSchema validation but this is not granular enough for my use case:

 const _key = await encryption.createDataKey('local', {
    keyAltNames: ['demo-data-key']
 await mongoose.connection.createCollection('Users', {
   validator: {
     $jsonSchema: {
        bsonType: 'object',
        properties: {
          lastName: {
            encrypt: {
              bsonType: 'string',
              keyId: [_key],
              algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }

Also in official documentation, this scenario is not covered because key always needs to be specified upfront and it is defined on collection or field level but never on document https://docs.mongodb.com/manual/reference/security-client-side-automatic-json-schema/

Any help, please?

1 Like

Were you able to figure this out? I need the same.

1 Like

Hi @Vishal_Rastogi1 and @Clement,

I just discovered this topic, I’m so sorry for not seeing it earlier.

I actually implemented this in Java in this blog post:

You can apply exactly the same logic with the Node Driver. It would work exactly the same way. In my version, I’m not using MongoDB Enterprise Advanced i.e. mongocryptd. I’m just using libmongocrypt to manipulate the data but I don’t use the automated encryption & decryption that mongocryptd provides. When you use the $jsonschema, you have to specify the single Data Encryption Key (DEK) that will encrypt this field for all the docs. It doesn’t work with the implementation you are trying to do i.e. one key for one user.


1 Like