Search code examples
mongodbmongodb-rubynosql

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


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?


Solution

  • 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'})