@Martin_Koslof I recommend using the “aggregate” method with the “$lookup” stage to join the collections based on a matching field. You can then use other stages such as “$project” or “$group” to shape the output of the view as needed. Here is an example of how to create a view from two collections:
db.createView("myView", "collection1", [
{
$lookup: {
from: "collection2",
localField: "commonField",
foreignField: "commonField",
as: "joinedData"
}
},
{
$unwind: {
path: "$joinedData",
preserveNullAndEmptyArrays: true
}
}
])
In the above example, the “myView” view is being created based on “collection1”. The “$lookup” stage is used to join “collection1” with “collection2” based on a common field called “commonField”. The resulting documents are then flattened using “$unwind” to create one document per matching pair of documents from the two collections.
Note that in order to create a view in MongoDB, you must have the “createView” privilege on the database.
Hope this was helpful ![]()