Home > Mobile >  How do I use $project on joined collections in MongoDB?
How do I use $project on joined collections in MongoDB?

Time:11-29

db.books.aggregate(
  [
    {
      $lookup: {
        from:'book_copies',
        localField:'ISBN10',
        foreignField:'book_id',
        as:'book_copies'
      }
    }
  ]
);

The code above simply make collection "books" join collection "book_copies", there are couple repeating value after join such as "id" and "book_id".

Content after $lookup: Content after $lookup

I would like to only keep branch_id and no_of_copies in book_copies. How do I do that?

db.books.aggregate(
  [
    {
      $lookup: {
        from:'book_copies',
        localField:'ISBN10',
        foreignField:'book_id',
        as:'book_copies'
      }
    },
    {
      $project: {
        ISBN10:1,
        ISBN13:1,
        Title:1,
        Cover:1,
        Publisher:1,
        Pages:1,
        Authors_arr:1,
        branch_id:1,
        no_of_copies:1
      }
    }
  ]
);

My attempt was to set branch_id and no_of_copies to 1, but this way just erased all content from book_copies.

content after project This is what expected to get Expected

CodePudding user response:

As @rickhg12hs suggests, please do not paste images. The actual text of the sample documents allows us to test and more appropriately suggest a solution to your problem.

Changing your $project to exclude the fields that you don't want should achieve your goals:

  {
    "$project": {
      "book_copies._id": 0,
      "book_copies.book_id": 0
    }
  }

Playground demonstration here.

Alternatively, you can use the approach by @Takis to do the $project inside of the $lookup itself:

  {
    $lookup: {
      from: "book_copies",
      localField: "ISBN10",
      foreignField: "book_id",
      as: "book_copies",
      pipeline: [
        {
          $project: {
            _id: 0,
            book_id: 0
          }
        }
      ]
    }
  }

Playground demonstration here.

  • Related