$elementMatch或$unwind与AND/Multiple条件与单数据库聚合


{
"_id": 1,
"user_response": [
{
"question_name": "Gender ?",
"question_numeric_id": 1,
"question_answer": "Male"
},
{
"question_name": "City ?",
"question_numeric_id": 2,
"question_answer": "GJ"
},
{
"question_name": "Country ?",
"question_numeric_id": 3,
"question_answer": "India"
}
]
}
{
"_id": 2,
"user_response": [
{
"question_name": "Gender ?",
"question_numeric_id": 1,
"question_answer": "Female"
},
{
"question_name": "State ?",
"question_numeric_id": 2,
"question_answer": "GJ"
},
{
"question_name": "Country ?",
"question_numeric_id": 3,
"question_answer": "India"
}
]
}
{
"_id": 3,
"user_response": [
{
"question_name": "Gender ?",
"question_numeric_id": 1,
"question_answer": "Male"
},
{
"question_name": "State ?",
"question_numeric_id": 2,
"question_answer": "GJ"
},
{
"question_name": "Country ?",
"question_numeric_id": 3,
"question_answer": "India"
}
]
}
{
"_id": 4,
"user_response": [
{
"question_name": "Gender ?",
"question_numeric_id": 1,
"question_answer": "Other"
},
{
"question_name": "State ?",
"question_numeric_id": 2,
"question_answer": "MP"
},
{
"question_name": "Country ?",
"question_numeric_id": 3,
"question_answer": "India"
}
]
}

这种情况就像我必须对Array的多个字段进行条件设置。例如:

question_numeric_id: 1 AND question_answer: Male和question_numeric_id: 2 AND question_answer: MP

所以,输出应该是:

{
"_id": 1,
"user_response": [
{
"question_name": "Gender ?""question_numeric_id": 1,
"question_answer": "Male"
},
{
"question_name": "City ?""question_numeric_id": 2,
"question_answer": "GJ"
},
{
"question_name": "Country ?""question_numeric_id": 3,
"question_answer": "India"
}
]
}
{
"_id": 3,
"user_response": [
{
"question_name": "Gender ?""question_numeric_id": 1,
"question_answer": "Male"
},
{
"question_name": "State ?""question_numeric_id": 2,
"question_answer": "GJ"
},
{
"question_name": "Country ?""question_numeric_id": 3,
"question_answer": "India"
}
]
}

我尝试了很多方法使用elementMatch和unwind,但没有获得成功。unwinds和elementMatch只对单个数组元素有效。如果你们能帮我,我会很感激的。由于

注意:请给出一个使用聚合的解决方案

您可以尝试使用$and关键字。

例如,在pymongo中:

data_access['your_collection'].find({
"$and": [
{"user_response.question_numeric_id": 1},
{"user_response.question_answer": "Male"},
{"user_response.question_numeric_id": 2},
{"user_response.question_answer": "MP"},
]
})

希望以上解决方案对你有用。

相关内容

  • 没有找到相关文章

最新更新