node.js - 如何对外键进行条件聚合查找
问题描述
经过多次尝试,我无法对我的集合进行良好的条件聚合。
我使用两个集合:
有评论集合的比赛。
我只需要为我的第二个管道获取已发布的评论。我不想使用$project
. 可以只使用$match
吗?当我使用 localField、foreignField 时,效果很好,但我只需要过滤已发布的评论。我为此苦苦挣扎,我不明白为什么let
不给我foreignKey。我试过: _id
, $reviews
, 等等..
我的$lookup
样子是这样的:
{
$lookup: {
from: "reviews",
as: "reviews",
let: { reviewsId: "$_id" },
pipeline: [
{
$match: {
$expr: {
$and: [
// If I comment the next line, it give all the reviews to all the races
{ $eq: ["$_id", "$$reviewsId"] },
{ $eq: ["$is_published", true] }
]
}
}
}
]
// localField: "reviews",
// foreignField: "_id"
}
},
比赛示例:
{
"description":"Nice race",
"attendees":[
],
"reviews":[
{
"$oid":"5c363ddcfdab6f1d822d7761"
},
{
"$oid":"5cbc835926fa61bd4349a02a"
}
],
...
}
评论示例:
{
"_id":"5c3630ac5d00d1dc26273dab",
"user_id":"5be89576a38d2b260bfc1bfe",
"user_pseudo":"gracias",
"is_published":true,
"likes":[],
"title":"Best race",
"__v":10,
...
}
我很快就会发疯:'(......如何做到这一点?
解决方案
首先,您必须采用正确的字段才能从引用的集合中获取数据,即reviews
. 其次,您需要使用$in
聚合运算符,因为您的reviews
字段是一个ObjectId
s 数组。
db.getCollection('races').aggregate([
{ "$lookup": {
"from": "reviews",
"let": { "reviews": "$reviews" },
"pipeline": [
{ "$match": {
"$expr": { "$in": [ "$_id", "$$reviews" ] },
"is_published": true
}}
],
"as": "reviews"
}}
])
推荐阅读
- reactjs - Onclick事件目标冒泡给孩子?
- c# - 删除 GridControl 和数据库中的多个选定行?
- swift - 不添加 UISearchController
- c - 玩家与地板碰撞时不会移动
- save - Slurm:不完整的作业状态保存文件,以'-i'开头忽略此
- javascript - 如何在 React 中按状态数组过滤数据对象?
- python - Django如何解决保存空表单问题?
- python - 如何使用`airflow create_user`在Docker容器上的Airflow 1.10.9中创建具有不同角色的用户?
- graphql - 在 mocha 中为 GraphQL API 使用 istanbul(nyc) 的代码覆盖率
- java - 如何从 Spring 集成文件中读取嵌套的 txt 文件