Hi @kevin_Morte_i_Piferrer,
Proper approach is a matter of opinion, but I would narrow this use case down to: if you have a single field that relates to multiple collections you may want to consider using DBRefs or an equivalent subdocument format.
However, I’d still be strongly inclined to use manual references (i.e. an equivalent subdocument format) since the DBRef BSON type will be more difficult to work with in server-side queries.
The full DBRef includes an _id
($id
), collection name ($ref
), and optional database name ($db
).
Borrowing the docs example:
"creator" : {
"$ref" : "creators",
"$id" : ObjectId("5126bc054aed4daf9e2ab772"),
"$db" : "users"
}
A manual reference might look like:
"creator" : {
"coll" : "creators",
"_id" : ObjectId("5126bc054aed4daf9e2ab772"),
"db" : "users"
}
If the related collection is in the same database, you could simplify to:
"creator_id": ObjectId("5126bc054aed4daf9e2ab772")
You would have to construct appropriate queries if you want to find or combine related data, but that is still the case with DBRefs. DBRefs have limited server-side support, and have to be resolved using additional queries to return the referenced documents.
Overall DBRefs are a legacy convention best avoided in modern applications using MongoDB.
Regards,
Stennie