Reputation: 697
I am new to mongodb so I am not sure what is the best practice. But I have seen many times the value in _id field is repeated.
db.memberrecords.find().limit(2).forEach(printjson)
{
"_id" : "999783",
"Memberid" : "999783",
"Name" : "ASHEESH SHARMA",
"Gender" : "M",
}
{
"_id" : "999784",
"Memberid" : "999784",
"Name" : "Sanwal Singh Meena",
"Gender" : "M",
}
For example here _id and Memberid does the same thing and store the same value
Is there any reason why we do so ? why do we have two fields that store the same result?
Upvotes: 0
Views: 60
Reputation: 1696
So going with the basics first
_id
is default id (primary key if you are coming from SQL) for mongoDB documents._id
is of type ObjectId
_id
_id
is always required for document, if its not there, it is automatically generated.So coming back to question, why duplicated values. It totally depends on how you plan you document structure. Some prefer to got with auto generated _id
as their primary key while others want to create and maintain it themselves or change its type.
In your case one possibility is that the creator wanted a meaningful key name and so they went with adding an extra field (memberId) to have whatever is in _id
and since _id
is required they end up maintaining both of these keys. It completely depends on creator and his opinion.
For more information on mongoDB documents, see this manual https://docs.mongodb.com/manual/core/document/
Upvotes: 1