Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to configure ObjectId default field's name in MongoDB?

Is it possible to change the ObjectId field name from '_id' to 'id', or something else?

I've been looking in the docs and so far haven't found anything concerning this. I'm using MongoDB with pymongo (python driver) on the server, where I'll provide JSON objects, and the js library I'm using on the client expects objects with an 'id' field.

like image 711
Diego Ponciano Avatar asked Feb 10 '12 18:02

Diego Ponciano


2 Answers

The database will always expect or add an "_id" field, but you can actually mask this from the client in some cases.

Check out the references on SON manipulators. You can transform documents as you insert them and extract them to dynamically change the "_id" field to appear as if it is an "id" field. Be warned, however, that this will only transform the document - NOT the queries: findOne({"id": "1234567890"}) won't find anything because the "id" field doesn't really exist in the database.

You will have to decide for yourself whether this is a good idea for your use case.

like image 148
mattbornski Avatar answered Sep 18 '22 22:09

mattbornski


I don't think so. The _id field is created automatically for every document created. You could create a different id field if you wanted to use something else like an integer value.

like image 28
SomethingOn Avatar answered Sep 19 '22 22:09

SomethingOn