Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制)

编程入门 行业动态 更新时间:2024-10-28 01:19:45
本文介绍了Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

mongoplayground/p/dsMlfEdSkXP

我想查询broadcasterUser 支持的文档.在链接中,broadcasterUser id 为23435553"

I want to query documents that the broadcasterUser upvoted. In the link, the broadcasterUser id is "23435553"

在结果中,不应返回带有 "_id": ObjectId("5e7d7c35d86d85088863f4df")," 的文档,因为广播公司的投票类型是 "downVote".

In the result, the document with "_id": ObjectId("5e7d7c35d86d85088863f4df")," should NOT be returned, because the broadcaster's voteType is "downVote".

应该返回带有_id"的文档:ObjectId("5e7d7c47d86d85088863f4e0"),因为广播公司的voteType是upVote".

The document with "_id": ObjectId("5e7d7c47d86d85088863f4e0") SHOULD be returned, because the broadcaster's voteType is "upVote".

为什么我的 $match 条件不起作用?

Why is my $match condition not working?

{ $match: { "votes.user.id": "23435553", "votes.voteType": "upVote", } }

找到我的答案,谢谢@prasad.mongoplayground/p/I_W0_BIIVVO

Found my answer, thanks @prasad. mongoplayground/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", } }, } }, ])

我没有尝试进行任何数组过滤.我试图根据数组中对象的存在来过滤文档.

I wasn't trying to do any array filtering. I was trying to filter documents, based on the presence of an object in an array.

第二个 $match 运算符的理想逻辑是找到建议文档,其中在 votes 数组中存在一个 user.id="23435553" AND voteType="upVote" 的对象.

The desired logic with the 2nd $match operator was "find suggestion documents where, in the votes array, there exists an object with user.id="23435553" AND voteType="upVote".

推荐答案

要从数组中返回特定元素,您需要对投影执行 $filter.而不是 $match,你的最后一个管道查询将是这样的

To return specific elements from an array, you need to do $filter on your projection. instead of $match, your last pipeline query will be something like this

{ $project: { _id: 1, user: 1, votes: { $filter: { input: "$votes", as: "item", cond: { $and: [ { $eq: [ "$$item.user.id", "23435553" ] }, { $eq: [ "$$item.voteType", "upVote" ] } ] } } } } }

解决方案也是在操场上完成的

The solution is also done in a playground

mongoplayground/p/J9O-HzHnQNP

更多推荐

Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制)

本文发布于:2023-11-22 19:02:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618627.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   不起作用   元素   Mongo   match

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!