![](/img/trans.png)
[英]How to find the sum of values that are inside a nested array using mongodb aggregation?
[英]mongodb aggregation "$in" operator: how can i address the path to all nested array elements inside an array
所以我想檢查一個元素是否在幾個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")
}}
聚合階段:
(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,
},
}),
嘗試了兩種方法。 而且我不斷收到此錯誤:“$in 需要一個數組作為第二個參數,找到:字符串”
有人知道如何解決這個問題嗎? 非常感謝
鑒於此輸入:
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"] }
]
}}
];
那么以下將 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.