【问题标题】:Mongoose find if some condition from other collectionMongoose 查找其他集合中的某些条件
【发布时间】:2019-03-08 00:51:08
【问题描述】:

我正在尝试在 Mongo 中执行以下查询,我需要一些帮助。 我有 2 个收藏:

集合 1 - users : {_id, name, lastname}

集合 2 - tutorial_finish : {user_id, completed}

我想选择其name 为“John Doe”的所有用户并且该用户不得 出现在集合2中

【问题讨论】:

    标签: mongodb mongoose aggregation-framework lookup


    【解决方案1】:

    您可以使用$lookup“加入”两个集合中的数据,然后使用$match 检查$lookup 创建的数组是否为空:

    db.users.aggregate([
        {
            $match: { name: "John", lastname: "Doe" }
        },
        {
            $lookup: {
                from: "tutorial_finish",
                localField: "_id",
                foreignField: "user_id",
                as: "tutorials"
            }
        },
        {
            $match: { tutorials: [] }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 2014-10-28
      • 1970-01-01
      • 2018-07-28
      • 2022-08-03
      • 2023-04-04
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 2016-02-20
      相关资源
      最近更新 更多