$element 匹配或 $unwind 与 AND/Multiple 条件与 mongoDB 聚合
Posted
技术标签:
【中文标题】$element 匹配或 $unwind 与 AND/Multiple 条件与 mongoDB 聚合【英文标题】:$elementMatch or $unwind with AND/Multiple condition with monogDB aggregate 【发布时间】:2021-11-12 20:54:09 【问题描述】:
"_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 : 男性 和 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 仅适用于单个数组元素。 如果你们能帮我解决这个问题,我将不胜感激。谢谢
注意: 请给出一个使用聚合的解决方案。
【问题讨论】:
欢迎您,请在您的问题中添加您的尝试,以改善您的体验,请使用tour 并阅读how to ask 一个好问题。 question_numeric_id:1 AND question_answer:男性 AND question_numeric_id:2 AND question_answer:MP。我认为你需要检查你的输出。如果你想要这个过滤器,输出将没有任何文档。因为 question_numeric_id : 2 AND question_answer : MP 没有出现在 id 1 和 3 的文档中。 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。 【参考方案1】:您可以尝试使用$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",
]
)
希望上述解决方案对您有用。
【讨论】:
以上是关于$element 匹配或 $unwind 与 AND/Multiple 条件与 mongoDB 聚合的主要内容,如果未能解决你的问题,请参考以下文章
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.al
MongoDB 操作符 $unwind 展开数组(agregation)
有没有办法使用 foreach 或 unwind 将 csv 导入 Neo4j?