mongodb - Mongo 聚合,对数组元素调用 $match 不起作用。(包括复制)
问题描述
https://mongoplayground.net/p/dsMlfEdSkXP
我想查询广播者用户赞成的文档。在链接中,broadcasterUser id 是“23435553”
结果,不应返回带有 "_id": ObjectId("5e7d7c35d86d85088863f4df")," 的文档,因为广播公司的 voteType 是 "downVote"。
应该返回带有“_id”的文档:ObjectId("5e7d7c47d86d85088863f4e0"),因为广播者的 voteType 是“upVote”。
为什么我的 $match 条件不起作用?
{
$match: {
"votes.user.id": "23435553",
"votes.voteType": "upVote",
}
}
编辑:找到我的答案,谢谢@prasad。https://mongoplayground.net/p/I_W0_BIIVVO
db.suggestions.aggregate([
{
$match: {
"channelId": "23435553",
}
},
{
$lookup: {
from: "votes",
localField: "_id",
foreignField: "suggestionId",
as: "votes"
}
},
{
$match: {
"votes": {
"$elemMatch": {
"user.id": "23435553",
"voteType": "upVote",
}
},
}
},
])
我没有尝试进行任何数组过滤。我试图根据数组中对象的存在来过滤文档。
第二个 $match 运算符所需的逻辑是“查找建议文档,其中在投票数组中存在 user.id="23435553" AND voteType="upVote" 的对象。
解决方案
要从数组中返回特定元素,您需要对$filter
投影进行操作。而不是$match
,您的最后一个管道查询将是这样的
{
$project: {
_id: 1, user: 1,
votes: {
$filter: {
input: "$votes",
as: "item",
cond: {
$and: [
{
$eq: [
"$$item.user.id",
"23435553"
]
},
{
$eq: [
"$$item.voteType",
"upVote"
]
}
]
}
}
}
}
}
解决方案也在操场上完成
推荐阅读
- html - 如何在没有表格的情况下做表格格式
- java - 从 Java 中的 String 对象检测文件类型(json、html、文本)
- amazon-web-services - 什么是快照或 EBS 中的根快照?
- python - 将反应应用于分子 RDKit 的消毒错误
- tableau-api - 需要帮助使用地图的两个数据源
- crystal-reports - 使用参数时,选择条件中需要一个数字
- http - http:ContentLength=99,正文长度为 0
- javascript - 如何使用 Laxxx.js 为盒子设置动画?
- algorithm - 有向平面图中最大 st 流的 O(n * log(n)) 算法(Borradaile,Klein)
- python - pip3 setup.py install_requires PEP 508 git URL 用于私人仓库