I have one collection, with the id of the documents set as MongoDb Object Ids (so appear in the db as:
Collection1
"someId": {
"$oid": "5003cb802e28076412000001"
},
In another collection, I am referencing these. However sometimes these references appear to be stored as proper oids:
Collection 2
"someForiegnId": {
"$oid": "5003cb802e28076412000001"
},
But other times they have made it into the db as a normal string.
Collection 2
"someForiegnId": "5003cb802e28076412000001",
My question is - Is is important to store these foreign references in the oid format, or can they just be strings?
MongoDB applications use one of two methods to relate documents: Manual references save the _id field of one document in another document as a reference. Your application runs a second query to return the related data. These references are simple and sufficient for most use cases.
We can join documents on collections in MongoDB by using the $lookup (Aggregation) function. $lookup(Aggregation) creates an outer left join with another collection and helps to filter data from merged data.
Object ID is treated as the primary key within any MongoDB collection. It is a unique identifier for each document or record. Syntax: ObjectId(<hexadecimal>). An ObjectId is a 12-byte BSON type hexadecimal string having the structure as shown in the example below.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.
I know that I am answering a 1 year old question, but still.
It is always desirable to be consistent in your database. No matter how you store your data (for example of IP address as a string "87.123.12.12"
an array [87, 123, 12, 12]
or a number 1467681804
) it should be always the same way. The same with your data: you have to select one format and stick with it.
The format you will select have implications on how much storage will you use and how fast you will be able to query the data. And the best way is to store them as ObjectID for the following reasons:
So even if I would have only string representations - I would change to ObjectID(), in your case this is definitely worth switching (I know that you most probably have already done so).
P.S. You can modify the field by modifying the query in the following answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With