Fabio Pereira
Fabio Pereira

Reputation: 47

How join/combine results from mongoDB

I'm dev a card game. I have a catalog of cards in my game, let's say table "Catalog":

[
  {
    "id": 1,
    "name": "my spell",
    "type": "spell",
    "cost": 120
  }
]

On another table (name playerCards) I have all the cards that a player has. On that structure I don't want to repeat all information I have set-up for the card on the catalog. I only need to store the id of the card and the amounts:

[
  {
    "id": 1,
    "card_count_in_book": 10,
    "card_count_in_deck": 1
  }
]

And I'd like to know how can I make a query to return all card from a player in the following format:

[
  {
    "id": 1,
    "card_count_in_book": 10,
    "card_count_in_deck": 1,
    "name": "my spell",
    "type": "spell",
    "cost": 120
  }
]

Upvotes: 1

Views: 34

Answers (1)

mickl
mickl

Reputation: 49985

Use $lookup operator to merge the data from both collections by id

db.Catalog.aggregate([
    {
        $lookup: {
            from: "playerCards",
            localField: "id",
            foreignField: "id",
            as: "playercards"
        }
    },
    {
        $unwind: "$playercards"
    },
    {
        $project: {
            id: 1,
            name: 1,
            type: 1,
            cost: 1,
            card_count_in_book: "$playercards.card_count_in_book",
            card_count_in_deck: "$playercards.card_count_in_deck",
        }
    }
])

Upvotes: 2

Related Questions