mongodb - 本地字段和外部字段不起作用的查找管道内的项目
问题描述
我在下面编写了一些代码行,用于在查找中获取一些特定字段,例如
$pipeline = array(
array(
'$match' => $query
),
array(
'$lookup' => array(
'from' => 'studentTbl',
'localField' => '_id',
'foreignField' => 'activity_details.activityId',
'pipeline' => [
['$project' => [ '_id' => 1.0, 'activity_details' => 1.0] ],
],
'as' => 'studentsOfActivities'
)
),
....
....
);
return $this->db->activitiesTbl->aggregate($pipeline)->toArray();
基本上 studentTbl 有很多字段和嵌入的文档。在上面的代码中,我首先使用外部和本地字段通过查找来获取,然后确定哪些字段应该投射到管道中。
上面的代码不起作用......请帮助!
解决方案
您可以使用以下聚合
db.collection.aggregate([
{ "$match": $query },
{ "$lookup": {
"from": "studentTbl",
"let": { "activityId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$$activityId", "$activity_details.activityId"] }}},
{ "$project": { "activity_details": 1 }}
],
"as": "studentsOfActivities"
}}
])
推荐阅读
- linux - 如何在 bash 中调试 Linux 中的参数问题
- sql - Firebird 是否支持 Infinity 作为 FLOAT 值?
- java - 如果计划的线程启动或不启动,有什么方法可以通知或回调?
- r - Roxygen2 无法处理以下划线开头的文件?
- python - 使用“wait_for”discord.py 等待反应时出错
- php - Google Ads Api 开发人员令牌错误 - 即使已验证
- python - 如何根据 facebook user_id 从 aws cognito 获取用户?
- android - Android DialogFragment 视图未更新
- javascript - 一旦进度条达到 100%,如何在 html 中将之前“禁用”的按钮设置为“启用”?
- swift - 将变量从 App 文件 SwiftUI 2 传递到 ContentView?