Can you create multiple indexes on a single field in Mongo? What does that look like?

812 views Asked by At

I'm trying to create a compound key as my "_id" field, which takes in some geo information as well as other attributes. It looks something like:

{_id: {lat: 50, lon: 50, name: "some name"}}

After creating the document, mongo assigns an index by default, and ignores my command

db.coll.ensureIndex(_id: "2d")

Is there a way to do this so I can have my _id field index-able by both geo-index and regular index?

2

There are 2 answers

0
Bernie Hackett On BEST ANSWER

You have two options here. Both of them require a change in your schema:

  1. Make _id a unique hash and put your coordinates in a separate field with a 2d index:

    {_id: "standard ObjectId or your hash", name: "some name", loc: [50, 50]}

  2. If you really want _id to be the only field (I wouldn't recommend this):

    {_id: {name: "some name", loc: [50, 50]}}

    db.coll.ensureIndex({'_id.loc': '2d'})

0
Michael Papile On

From the MongoDB documentation:

Users are welcome to use their own conventions for creating ids; the _id value may be of any type, other than arrays, so long as it is a unique. Arrays are not allowed because they are Multikeys.

You would also have to ensure these are unique too. Also this will mess with some things that presume you have a BSON ID

I would just index those fields on their own and make a compound index.

http://www.mongodb.org/display/DOCS/Object+IDs