1

I want to create unique index to a collection using Mongo-Scala Driver. This driver is new and also I am new to Scala. I am not able to create index via both these two methods.

collQueries.createIndex(Document("name" -> 1, "unique" -> true))

And this:

collQueries.createIndex(Document("name" -> 1, "unique" -> true), IndexOptions())

Can anyone please help on how to create unique index in Mongo-Scala driver as it is very new and not much information is available.

rg41
  • 131
  • 2
  • 6

2 Answers2

2

To create unique index i use this code:

collection.createIndexes(
    Seq(
        IndexModel(
            Indexes.ascending("name"),
            IndexOptions().background(false).unique(true)
        )
    )
)

I found very useful this quick documentation tour.

Enjoy!

mkUltra
  • 2,828
  • 1
  • 22
  • 47
1

From the official documentation:

The Indexes class provides static factory methods for all the MongoDB Index key types. Each method returns an instance of the Bson type, which can in turn be used with the createIndex methods.

Via IndexOptions you can set uniqueness and other options.

See here, here, here and here.

Christian
  • 4,543
  • 1
  • 22
  • 31
  • 1
    Can you please tell the syntax by how it can be done. I am not able to use IndexOptions. – rg41 Nov 20 '15 at 15:26
  • collQueries.createIndex(Document("name" -> 1), new IndexOptions().unique(true)) This is not creating any unique index on "name" in the database. – rg41 Nov 22 '15 at 18:59
  • This is just a shot in the dark, but what happens if you use Indexes.ascending or Indexes.descending instead of constructing the Bson Document yourself? – Christian Nov 23 '15 at 08:30