Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-14361

Compound Sparse Unique indexes behaviour is not properly specified

      Description

      The documentation is not complete for compound sparse unique index.

      Documentation mention if the key is omitted, then it won't trigger an error.

      But that's not true for compound indexes where one key (but not all) is omitted:

      ```javascript
      const

      { MongoClient }

      = require('mongodb');

      async function run() {
      const client = await MongoClient.connect(
      'mongodb://127.0.0.1',

      { useNewUrlParser: true, useUnifiedTopology: true, }

      ,
      );

      try {
      const db = await client.db('test');

      await db.dropCollection('scores').catch(() =>

      { /* no-op */ });
      await db.dropCollection('scores-other').catch(() => { /* no-op */ }

      );

      await db.collection('scores').createIndex(

      { score: 1, attempt: 1 }

      ,

      { unique: true, sparse: true, }

      ,
      );

      // Works
      try {
      await db.collection('scores').insertOne(

      { userid: 'AAAAAAA', score: 43, attempt: 1 }

      );
      await db.collection('scores').insertOne(

      { userid: 'BBBBBBB', score: 34, attempt: 2 }

      );
      } catch (e)

      { console.log('KO #1', e); }

      try {
      // Works because key is omitted
      await db.collection('scores').insertOne(

      { userid: 'CCCCCCC' }

      );
      await db.collection('scores').insertOne(

      { userid: 'DDDDDDD' }

      );
      } catch (e)

      { console.log('KO #2', e); }

      try {
      // Not working: key is not considered as omited https://docs.mongodb.com/manual/core/index-sparse/#sparse-and-unique-properties
      await db.collection('scores').insertOne(

      { userid: 'CCCCCCC', attempt: 1 }

      );
      await db.collection('scores').insertOne(

      { userid: 'DDDDDDD', attempt: 1 }

      );
      } catch (e)

      { console.log('KO #3', e); }

      } catch (err)

      { console.error(err); }

      finally

      { client.close(); }

      }

      run();
      ```

      I am not sure if this requires a documentation update or a bug fix.

      Scope of changes

      Impact to Other Docs

      MVP (Work and Date)

      Resources (Scope or Design Docs, Invision, etc.)

            Assignee:
            Unassigned Unassigned
            Reporter:
            moroine.bentefrit@gmail.com moroine bentefrit
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              1 year, 25 weeks, 2 days ago