首页 > 解决方案 > 如何从集合中的其他集合中获取与列表字段元素的值匹配的文档

问题描述

我有两个集合,一个是项目集合,另一个是批量集合

两个集合看起来像这样

集合“项目”:

{
    "_id" : ObjectId("6102780c27474af56cf6734b"),
    "channel" : "instagram",
    "status" : "new",
    "analysis_type" : "detail",
    "batch_ids" : [ 
        "6102780c27474af56cf6734d", 
        "6102780d27474af56cf6734f", 
        "6102780d27474af56cf67351", 
        "6102780e27474af56cf67353", 
        "6102780e27474af56cf67355", 
        "6102780e27474af56cf67357"
    ]
}

集合“批次”:

    "_id" : ObjectId("6102780c27474af56cf6734d"),
    "keyword" : {
        "keyword" : "tomato",
        "keyword_type" : "hashtag"
    },
    "channel" : "instagram",
    "post_datetime" : ISODate("2021-07-29T18:42:36.306Z"),
    "analysis_type" : "detail",
    "status" : "new",
}

一个项目包含多个批次。因此,在名为 batch_ids 的字段中,我记下了项目包含哪些批次。batch_ids 字段的每个元素都是批处理集合的 _id 字段的值。我想立即查看属于某个项目的批次的状态。如何创建视图?我想看到的结果是:

{
    "_id" : ObjectId("6102780c27474af56cf6734b"),
    "channel" : "instagram",
    "status" : "new",
    "analysis_type" : "detail",
    "batch_ids" : [ 
        {
         "_id":ObjectId("6102780c27474af56cf6734d"),
         "status":"new"
        },
        {
         "_id":ObjectId("6102780d27474af56cf6734f"),
         "status":"new"
        },
        {
         "_id":ObjectId("6102780d27474af56cf67351"),
         "status":"new"
        },
        {
         "_id":ObjectId("6102780e27474af56cf67353"),
         "status":"new"
        },
        {
         "_id":ObjectId("6102780e27474af56cf67355"),
         "status":"new"
        },
        {
         "_id":ObjectId("6102780e27474af56cf67357"),
         "status":"new"
        },
    ]
}

标签: mongodbnosqlaggregation-framework

解决方案


一个简单的$lookup就足够了:

db.project.aggregate([
  {
    "$lookup": {
      "from": "batch",
      "let": {
        batchObjectIds: {
          $map: {
            input: "$batch_ids",
            as: "batch_id",
            in: {
              "$toObjectId": "$$batch_id"
            }
          }
        }
      },
      "pipeline": [
        {
          $match: {
            $expr: {
              $in: [
                "$_id",
                "$$batchObjectIds"
              ]
            }
          }
        },
        {
          $project: {
            _id: 1,
            status: 1
          }
        }
      ],
      "as": "batch_ids"
    }
  }
])

*请注意,因为您保存的是batch_idsasstring而不是objectId我们必须将它们强制转换为ObjectId使用toObjectId ,这意味着这仅适用于 Mongo v4.0+。如果您使用的是较小的 Mongo 版本,则必须将其拆分为 2 个调用。

蒙戈游乐场


推荐阅读