pferrel
pferrel

Reputation: 5702

MongoiDB use a String for _id

I'd like to use a unique string per collection to id a doc. I'm using Scala and Casbah but can also use Java if needed.

I know I should use Casbah collection.createIndex but I don't understand the scaladocs.

If my case class is :

case class GroupParams (
  _id: String,
  //groupId: String,
  testPeriodStart: DateTime, // ISO8601 date
  variants: Seq[String], //["17","18"]
  testPeriodEnd: Option[DateTime])

and I will always use the _id to reference a particular document (no need for _id: ObjectId).

I don't care about sorting/ordering since these will only be accessed as individual docs, never cursored through. There seems no reason to have the overhead of another index on the default _id: ObjectId.

How to I create the index on the collection with _id: String using Casbah? If I should create a new index and leave the default alone can you show how to do this?

Upvotes: 0

Views: 183

Answers (2)

Daniel Taub
Daniel Taub

Reputation: 5359

Mongo automatically generate a _id to your index in the collection,
if you want to insert String to the _id you can convert a String to objectId like this : ObjectId.Parse(myString))

See more in the MongoDB API

Upvotes: 0

Arthur Kushner
Arthur Kushner

Reputation: 99

Mongo automatically creates index for _id field for all types (ObjectId, String or whatever you want) - mongo indexes

Upvotes: 0

Related Questions