【问题标题】:MongoDB / Mongoose query to find if an ID exist in another document , if exist add a flag in resultMongoDB / Mongoose查询以查找ID是否存在于另一个文档中,如果存在则在结果中添加一个标志
【发布时间】:2021-04-11 00:05:34
【问题描述】:

问题定义:

我们有 2 个集合 User(存储用户数据)和 UserTransactions(存储用户完成的交易)。用户有 2 个usertypes“父母”和“学生”。

用户架构

{
    _id : ---
    name : String
    usertype : String // parent/student
    studententity : [] // It will store _id of related students from same document
}

UserTransaction 架构

{
    _id : ---
    ref_id: // id of parent who is doing transaction
}

我们需要获取的数据包括

  1. 所有家长名单
  2. 家长下的学生名单
  3. 如果父母完成了“任何”交易。

我们可以通过运行查询轻松获得第一个和第二个条件

User.find({ "usertype": { $eq: "parent" } })
    .populate("studententity")

但我们还想获得有关父母是否进行过“任何”交易的信息。获取这些数据的最佳方式是什么?

我的预期结果是这样的

{
    "usertype": "parent",
    "studententity": [
        {
            "usertype": "student",
            "_id": "5f8a6d0900e0030c7031d56a",
            "name": "Adya"
        },
        { 
            "usertype": "student",
            "_id": "5f9bb96fdf44b931b40c6043",
            "name": "Aruja"
        }
    ],
    transactionflag : true // a flag that signifies transaction is done 
}

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    可以使用$lookup$addFields 阶段来获得所需的结果。

    db.user.aggregate([
      {
        "$lookup": {
          "from": "transaction",
          "localField": "_id",
          "foreignField": "ref_id",
          "as": "transactionflag"
        }
      },
      {
        "$addFields": {
          "transactionflag": {
            $toBool: {
              $size: "$transactionflag"
            }
          }
        }
      }
    ])
    

    https://mongoplayground.net/p/j0lL4uCgCtA

    【讨论】:

      猜你喜欢
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2018-12-14
      • 2021-11-12
      • 2012-07-10
      • 1970-01-01
      相关资源
      最近更新 更多