【问题标题】:How to JOIN two collection by _id with where condition in Mongodb and NodeJS如何通过 _id 在 Mongodb 和 NodeJS 中使用 where 条件加入两个集合
【发布时间】:2020-09-15 01:11:56
【问题描述】:

我有两个集合,称为用户和订阅,每个订阅都有 user_id,即用户集合的 _id。如何通过 is_account_active = 1 的 where 条件加入这两个集合。

请检查我正在使用的以下代码:

const users = await User.find({ is_account_active: 1 });

这将使我得到所有 is_account_active 标志为 1 的用户,但同时,我还想要订阅详细信息以及各自的用户 ID。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您可以使用例如aggregate 函数。 如果您将 user_id 保留为字符串并且您的 mongo db 版本 >= 4.0,那么您可以将 _id 转换为字符串(因为 _id 是 ObjectId 类型):

    const users = await User.aggregate([
      {
        $match: {
          is_account_active: 1
        }
      },
      {
        $project: {
          "_id": {
            "$toString": "$_id"
          }
        }
      },
      {
        $lookup: {
          from: 'subscriptions',     //collection name
          localField: '_id',
          foreignKey: 'user_id',
          as: 'subscription'.        //alias
        }
      }
    ]);
    

    但在订阅模式中将 user_id 存储为对象 id 会更好

    user_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref:'User'
    }
    

    那么

    const users = await User.aggregate([
      {
        $match: {
          is_account_active: 1
        }
      },
      {
        $lookup: {
          from: 'subscriptions',     //collection name
          localField: '_id',
          foreignKey: 'user_id',
          as: 'subscription'.        //alias
        }
      }
    ]);
    

    More about ObjectId

    More about Aggregate function

    【讨论】:

    • 它返回一个空数组
    • 您将 user_id 保留为 ObjectId 还是字符串?也许您应该发布一些您想要获取的用户和订阅集合中的数据,如果没有一些信息真的无济于事。 @KunalDholiya
    • 是的,是字符串
    【解决方案2】:

    您可以在下面查询。

    const users = await User.aggregate([
      {
        $match: {
          your_condition
        }
      },
      {
        $lookup: {
          from: 'subscriptions', // secondary db
          localField: '_id',
          foreignKey: 'user_id',
          as: 'subscription' // output to be stored
        }
      }
    ]);
    

    但与其使用 _id 作为外来语,不如使用新的 像 user_id 这样的字段在主集合中,并且可以在该字段上使用自动增量,现在将自动插入具有新唯一 ID 的新数据,并且您可以在其上创建索引以更快地执行查询。

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 1970-01-01
      • 2021-12-22
      • 2017-08-10
      • 2020-09-03
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多