How to create mongodb collection without _id

4.6k Views Asked by At

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"?

2

There are 2 best solutions below

3
On BEST ANSWER

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.

0
On

in mongoDB v3.4,you can create a collection without _id index.

Use the following statement:

db.createCollection("myCollection", { autoIndexId: false })