Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between _id & $oid ; $date & IsoDate in mongo database

We are using mongo db to store certain records in production database.

We see our records having "_id" : { "$oid" : "50585fbcb046b2709a534502"} in production database , while we see same record as "_id" : ObjectId(" 50585fbcb046b2709a534502 ") in the qa database. For dates we see "ld" : { "$date" : "2011-12-03T17:00:00Z"} in prod database, while "ld" :ISODate("2011-12-03T17:00:00Z") in qa database. We have tested our queries successfully in qa environment, but worried it might fail in production

1) Will my java queries work seamlessly on prod & qa both? (I am using morphia apis to query) 2) Are they internally being stored in the same identical way?

like image 334
Kumar Manish Avatar asked Sep 26 '12 10:09

Kumar Manish


People also ask

What is the difference between _id and id?

The _id field is the default field for Bson ObjectId's and it is,by default, indexed. _id and id are not the same. You may also choose to add a field called id if you want, but it will not be index unless you add an index. It is just a typo in the docs.

What is difference between id and _id in mongoose?

From the documentation: Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.

Why do we use _id in MongoDB?

_id is the primary key on elements in a collection; with it, records can be differentiated by default. _id is automatically indexed. Lookups specifying { _id: <someval> } refer to the _id index as their guide. Users can also override _id to something other than an ObjectID data type, if desired.

Should I use _id in MongoDB?

You should NOT convert the ObjectId in the database to a string, and then compare it to another string. If you'd do this, MongoDB cannot use the _id index and it'll have to scan all the documents, resulting in poor query performance.


1 Answers

To answer the two questions:

  1. Yes they will
  2. Yes they are the same, it is merely the representation within the item you are looking in (console or app) as to how they display. Console (later versions anyway, about 1.4+) will display ObjectId and ISODate (normally) whereas picking it out directly from the server language (Java in your case) will tend to show the full objects properties ($oid and $date in this case).
like image 128
Sammaye Avatar answered Oct 14 '22 00:10

Sammaye