【问题标题】:Set lookup variable to be the value of an expression将查找变量设置为表达式的值
【发布时间】:2021-03-28 11:58:52
【问题描述】:

这是我noteCollection的文档示例

{
  title: "Some title",
  body: "Descreptive body",
  contributedBy: [
    {
     contributorId: ObjectId(5353ff535f5f3a5)
    }
  ] // for some reason, this field has to be an array of objects
}

现在,在使用 $lookup“查找”贡献者时,我需要 contributorId 字段

问题是,我不知道如何用MongoDB查询方式表达contributedBy[0].contributorId

// lookup aggregation

{
  from: 'contributors',
  as: 'contributor',
  let: {'contributorUserId': '$contributedBy[0].contributorId'}, // here, how to get the value of `contributorId` property of the 0th element in `contributedBy` field
  pipeline: [
    {$match: {
     $expr: {$eq: ['$_id', '$$contributorUserId']} 
    }}   
  ]
}

【问题讨论】:

    标签: javascript mongodb mongodb-query aggregation-framework


    【解决方案1】:

    如果您想在0th 索引处仅通过一个contributedBy.contributorId 加入这两个集合,请使用$arrayElemAt 运算符:

    db.noteCollection.aggregate([
        {
            $lookup: {
                from: 'contributors',
                as: 'contributor',
                let: { 
                    'contributorUserId': {
                        $arrayElemAt: ['$contributedBy.contributorId', 0]
                    }
                },
                pipeline: [
                    {
                        $match: {
                            $expr: { $eq: ['$_id', '$$contributorUserId'] }
                        }
                    }
                ]
            }
        }
    ])
    

    如果您想将这两个集合加入到它们的引用 _ids 中,请使用 $in 运算符:

    db.noteCollection.aggregate([
        {
            $lookup: {
                from: 'contributors',
                as: 'contributor',
                let: { 
                    'contributorUserIds': '$contributedBy.contributorId'
                },
                pipeline: [
                    {
                        $match: {
                            $expr: { $in: ['$_id', '$$contributorUserIds'] }
                        }
                    }
                ]
            }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2018-10-31
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多