【问题标题】:Perform a join on a collection only WHERE substring matches仅对集合执行连接 WHERE 子字符串匹配
【发布时间】:2019-04-29 16:17:42
【问题描述】:

我想对一个集合执行连接,其中学生姓名在每个集合中都相等,并且列 log's 值中 "_" 之后的最后一个字符串是什么变量 id 是。

我得到了加入工作,但问题出在 match 语句上。如何匹配我即将加入的集合中 logs 列上的字符串的子字符串?

我可以将日志列值拆分成这样的数组:

{ $split: [ "$studentInfo.log", "_" ]}

我现在只需要获取下划线后的最后一个值来匹配变量id

var id = "123";

dbo.collection("student").aggregate([
{ "$lookup": {
    "localField": "name",
    "from": "data",
    "foreignField": "data.studentName",
    "as": "studentInfo"
}
}]).toArray(function(err, results) {
    console.log(results);
});

问题是学生姓名不是唯一的,所以为了让连接正常工作,我们需要按名称连接,并确保下划线后面的字符与我们拥有的变量匹配 id

学生收藏

{
    "_id" : ObjectId("(Object ID here"),
    "name": "Test"
}

数据收集

{
    "_id" : ObjectId("(Object ID here"),
    "studentName": "Test",
    "log": "NC_Test_123"
},
{
    "_id" : ObjectId("(Object ID here"),
    "studentName": "Test",
    "log": "FC_Test_444"
}

当我的 id 变量为 123 时,我需要得到 NC_Test_123

【问题讨论】:

  • 您能展示两个集合中的示例文档吗?
  • @mickl 编辑了帖子。请检查

标签: arrays mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您需要使用以下两个条件定义自定义 lookup condition:学生姓名和 log 字段。要获取拆分字符串的最后一个值,您可以使用$arrayElemAt,索引设置为-1

db.student.aggregate([
    {
        $lookup: {
            from: "data",
            let: { "student_name": "$name" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: [ "$$student_name", "$studentName" ] },
                                { $eq: [ { $arrayElemAt: [ { $split: [ "$log", "_" ]}, -1 ] }, "123" ] }
                            ]
                        }
                    }
                }
            ],
            as: "studentInfo"
        }
    },
    {
        $unwind: "$studentInfo"
    }
])

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多