So basically I am trying to query a collection with respect to another collection. More specifically, I have an items collection and a purchases collection. The purchases collection's documents hold references to an item document and a user document via their ObjectId like so:
Purchase:
type Purchase struct {
Id primitive.ObjectID `json:"id" bson:"_id"`
UserId primitive.ObjectID `json:"userId" bson:"userId"`
ItemId primitive.ObjectID `json:"itemId" bson:"itemId"`
}
An item document looks like this:
type Item struct {
Id primitive.ObjectID `json:"id" bson:"_id"`
Name string `json:"name" bson:"name"`
Price float64 `json:"price" bson:"price"`
LastBought time.Time `json:"lastBought" bson:"lastBought"`
}
Essentially, I want to search through a user's purchases by the name of the item. The issue obviously is, the purchase documents only hold the ids of the items, not the name or price since they could potentially change.
I am not too familiar/good with MongoDB and therefore don't know how to make complex queries like this one.
How could I do something like this as efficiently as possible?
Thank you!
Edit:
My current thought process towards a solution is:
- Perform a search on the
itemscollection via their name. - Take all the
_id's from theitemsdocuments returned from the search and get all thepurchasesdocuments that fit that filter.
This seems kind of inefficient so I am not too sure.