To avoid having to look up referenced documents, one practice is to embed them (e.g. https://docs.mongodb.com/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/).
Is there a way to have those embedded documents actually be separate and be referenced yet be "automatically embedded" like by some sort of functionality which automatically stores their data in the document which is referencing them – almost like an automatic "embedding cache" of sorts.
I'm not referring to them being automatically retrieved by reference, but an actual copy being stored and updated automatically.
I know this could be built manually, but I'm wondering what may exist already which can do this, preferably something inherent to MongoDB, but it doesn't have to be.
While I'm asking this about MongoDB in particular, if someone knows of something like this for other NoSQL databases, I'd be interested to hear about that as well as an answer.
Best Answer
You may be looking for MongoDB Aggregation pipeline stage $lookup.
Example: A collection
orders
contains the following documents:Another collection
inventory
contains the following documents:The following aggregation operation on the
orders
collection joins the documents fromorders
with the documents from theinventory
collectionExample output:
See more examples.
You could combine
$lookup
with $out stage to create another collection. See related $graphLookup