2

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:

  1. Perform a search on the items collection via their name.
  2. Take all the _id's from the items documents returned from the search and get all the purchases documents that fit that filter.

This seems kind of inefficient so I am not too sure.

  • 2
    For queries involving documents from multiple collections, use the [aggregation pipeline](https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/), notably the [`$lookup` stage](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/) to "bring in" documents from other collections. There are numerous tutorials on the topic on the net. – icza Jun 30 '22 at 06:16

0 Answers0