Search code examples
javamongodbscalamongodb-javamongodb-java-3.3.0

how to use compound index in mongodb using java/scala


I want to create an index on both fields a and b but I want the b field to be unique only I am not sure how can I achieve this in using compound index please help here is the code

var index=collectionMongo("test").createIndex(new BasicDBObject("a", 1))

var index1=collectionMongo("test").createIndex(new BasicDBObject("b", 1),new BasicDBObject("unique", true))

how can i perform my desired task in a compound index please help


Solution

  • The way I look at it, you're already doing it right since index intersection should handle the compound index for you. You've created an index for a and a unique index for b and mongo will use both of them when you perform a query that accepts both the fields.

    You can check out if the index is properly utilized by running db.find({"query involving a and b here"}).explain("executionStats")

    Intersection indexes may be favourable to a compound index if you need to index many fields (single and compounded) since it reduces the disk space needed as a whole.