Search code examples
mongodbgrailsgorm-mongodbgmongo

How to create mongodb collection without _id


My project was build on GMONGO framework and all the domains were created with attribute id as a string.So grail frame work will create mongodb collections with _id attribute when application is app. In UI there was a limitation to retrive _id.So in service "_id" is rewrite to "id" to overcome the issue. Could we created collections with "id" by default rather than "_id"?


Solution

  • No you cant. Mongo will automaticaly create _id if you dont specify any.

    https://docs.mongodb.com/v3.2/reference/glossary/

    In your case you can add index to id field, and when run queries just add projection to exclude _id.

    So you will have something like this in data

    {_id: mongoDbID, id: yourId, ...}

    And run query like this

    collection.find({id: yourId}).project({_id: 0}).toArray();

    You will get this as an result

    {id: yourId, ...}

    Hope this helps.