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 不起作用.(包括复制)
发布评论