Return 连接两个集合的电影对象数组

Return an array of movie objects by connecting two collections

我收集了用户、电影和心愿单。

用户已经存储在变量user_email中,我想获取所有movie 个与 wishlist 中存储的对象具有相同 ID 的对象。以下是一些模式和数据类型:

样本:

user_email: shangchi@gmail.com

电影 电影架构:

const movieSchema = mongoose.Schema({ 
    image: String, 
    title: String, 
    rating: String, 
    length: String, 
    // timeslots: Array
    timeslots: [{
        id: Number, 
        time: String, 
        seats: []
    }]
});

电影数据样本:

_id: 61d65a3431a314f4fc7e9170
image: "https://static.onecms.io/wp-content/uploads/sites/20/2021/08/25/spence..."
title: "Spencer"
rating: "R"
length: "1 hr 57 min"
timeslots: Array
__v: 0

愿望清单 愿望清单架构:

const wishlistSchema = mongoose.Schema({ 
    user: String, 
    movie: Schema.ObjectId
}

心愿单中的所有数据:

_id: 61ea4e67984f981ee529c008
user: "shangchi@gmail.com"
movie: 61d65a3431a314f4fc7e9170
__v: 0

_id: 61ecf6f6c7b93b96890c9ebb
user: "shangchi@gmail.com"
movie: 61e3a7bed4f5306388103156
__v: 0

_id: 61ecf73c9f651a07079c9641
user: "hello@gmail.com"
movie: 61e3acc21d84993477d89a22
__v: 0

_id: 61ecf73e9f651a07079c9644
user: "hello@gmail.com"
movie: 61d65a3431a314f4fc7e9170
__v: 0

如何获取Wishlist 集合中所有movies 与shangchi 电子邮件匹配的所有电影对象的数组?

$lookup.

db.movie.aggregate([
  {
    $lookup: {
      from: "wishlist",
      let: {
        movieId: "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$movie",
                    "$$movieId"
                  ]
                },
                {
                  $eq: [
                    "$user",
                    "shangchi@gmail.com"
                  ]
                }
              ]
            }
          }
        }
      ],
      as: "wishlist"
    }
  }
])

Sample Mongo Playground


参考

Perform Multiple Joins and a Correlated Subquery with $lookup

由于您使用的是 mongoose,因此您可以通过填充电影字段对心愿单集合执行简单的查找查询。

const wishlistMovies = await Wishlist.find({ 
  user: "shangchi@gmail.com" 
}).populate("movie", null, "Movie")

这将 return 电子邮件为 shangchi@gmail.com 的用户的心愿单电影列表,其中电影 ID 将被电影文档替换。