mongodb - 如何从集合中的其他集合中获取与列表字段元素的值匹配的文档
问题描述
我有两个集合,一个是项目集合,另一个是批量集合
两个集合看起来像这样
集合“项目”:
{
"_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"
},
]
}
解决方案
一个简单的$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_ids
asstring
而不是objectId
我们必须将它们强制转换为ObjectId
使用toObjectId ,这意味着这仅适用于 Mongo v4.0+。如果您使用的是较小的 Mongo 版本,则必须将其拆分为 2 个调用。
推荐阅读
- r - 从 R 中使用 GageRR/GageRRDesign 生成的数据帧中提取
- javascript - 如何在基于 React js 的 Web 应用程序中获取设备 ID?
- c++ - 在函数中使用布尔“recursiveCall”参数是一种好习惯吗?
- minimum-spanning-tree - 查找所有 MST 解决方案
- laravel - 路线 [foo/1/bar] 未定义
- r - 当嵌套循环包含在库中时,如何在 R 中使用嵌套并行化?
- ballerina - 在 Ballerina 中创建和使用枚举的惯用方式是什么?
- c# - 用户只能在管理员批准后注册
- java - 使用 docker 和 logback 记录到文件
- javascript - 如何从同一类中的另一个方法检索最后插入的 id?