[英]mongodb aggregation "$in" operator: how can i address the path to all nested array elements inside an array
So i want to check if an element is in few arrays. the number of arrays can change between 2 to 4. the structure of data is as follows:所以我想检查一个元素是否在几个arrays中。arrays的数量可以在2到4之间变化。数据结构如下:
{"question" : {
"answers" : [
{
"answerText" : "7000",
"_answerVotes" : []
},
{
"answerText" : "15000",
"_answerVotes" : []
},
{
"answerText" : "45000",
"_answerVotes" : []
},
{
"answerText" : "80000",
"_answerVotes" : []
}
],
"expireTime" : ISODate("2022-12-14T15:58:11.453Z")
}}
aggregation stage:聚合阶段:
(addFields.isUserVotedAnswerd = {
$cond: {
if: {
$in: [ObjectId(user), "question.answers.$._answerVotes"],
},
// $or: [
// { $in: [ObjectId(user), "$question.answers.0._answerVotes"] },
// { $in: [ObjectId(user), "$question.answers.1._answerVotes"] },
// { $in: [ObjectId(user), "$question.answers.2._answerVotes"] },
// { $in: [ObjectId(user), "$question.answers.3._answerVotes"] },
// ],
// },
then: true,
else: false,
},
}),
Tried both approaches.尝试了两种方法。 And I keep getting this error: "$in requires an array as a second argument, found: string "而且我不断收到此错误:“$in 需要一个数组作为第二个参数,找到:字符串”
Anybody know how to address this?有人知道如何解决这个问题吗? Many thanks非常感谢
Given this input:鉴于此输入:
var r = [
{question: {
"answers" : [
{"answerText" : "7000", "_answerVotes" : ["U1"] },
{"answerText" : "15000", "_answerVotes" : ["U2","U7"] }
]
}},
{question: {
"answers" : [
{"answerText" : "7000", "_answerVotes" : ["U2"] },
{"answerText" : "15000", "_answerVotes" : ["U9"] }
]
}},
{question: {
"answers" : [
{"answerText" : "7000", "_answerVotes" : ["U7"] }
]
}}
];
then the following will select only those docs where at least one user ID in any of the _answerVotes
in the answers
array matches the target:那么以下将 select 只有那些文档,其中answers
数组中的任何_answerVotes
中的至少一个用户 ID 与目标匹配:
var target_user = 'U2'; // user is string here but could be ObjectId
db.foo.aggregate([
{$project: {'X': {$filter: {input: '$question.answers',
as: 'z',
cond: {$in:[target_user,'$$z._answerVotes']}
}}
}}
,{$match: {$expr: {$ne:[0,{$size:'$X'}] } }}
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.