2

Every time I do a change to schema, Like I added unique index or set "sparse: true" to a field, I have to drop the collection for the changes to get applied. This is not possible for me in production server. Is there any other way to do apply the changes to collections without dropping it? I am new to mongodb. Since I am using mlab, I am not able to restart the mongo service also. Please help me with this.

Note : I am using nodejs version 4.2.0, mongoose 4.4.7, mongodb 3.2.9(I am using mlab).

Community
  • 1
  • 1
logesh
  • 303
  • 2
  • 8
  • 2
    what do you mean, you need to drop a collection when add unique index or set sparse? That is 100% false. – sergiuz Oct 25 '16 at 10:40
  • 1
    Can you provide the code you are using to apply this index. You should most certainly not need to drop your collection in order to apply an index – pieperu Oct 25 '16 at 11:11
  • I dont think you need to drop the whole collection for this, if your index field is present in the new document. can u share the new and old document? – rushUp Jan 10 '17 at 06:42

1 Answers1

1

There is no need to Drop the collection and recreate it when there is a change in schema.

More Info:

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field. The index is “sparse” because it does not include all documents of a collection. By contrast, non-sparse indexes contain all documents in a collection, storing null values for those documents that do not contain the indexed field.

sparse Index and Incomplete Results

If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index unless a hint() explicitly specifies the index.

Having a sparse index doesn't prevent us in inserting records with or without the sparse index field, that is enough for us to handle the schema change.

Please see the below collection

Collection marks
{_id:1, sub1: 67, sub2: 78, sub3: 56, total: 201}
{_id:2, sub1: 60, sub2: 70, sub3: 50, total: 180}
{_id:3, sub1: 80, sub2: 70, sub3: 50}

Create sparse index

db.marks.createIndex( { total: 1 } , { sparse: true, unique: true } )


db.marks.find().sort( { total: -1 } )
This query will return all the 3 records, we have applied sort on the sparse indexed field, but MongoDB will not select the sparse index to fulfill the query in order to return complete results.

db.marks.find().sort( { total: -1 } ).hint( { total: 1 } ), this query will return only 2 records, those who are having the total, so to use the sparse index, explicitly specify the index with hint()

References

https://docs.mongodb.com/manual/core/index-sparse/

https://docs.mongodb.com/manual/core/index-sparse/#sparse-index-incomplete-results

Hope it Helps!

Clement Amarnath
  • 5,301
  • 1
  • 21
  • 34