我要查询数组以获取mongo db
样本数据
在数据中,我有多个字段数组,其中包含不是强制性的动态字段名称,并且其位置将是随机的。我想为所有字段提取一个特定的标题及其值。
{
"_id" : NumberInt(2),
"categories" : [
{
"sections" : [
{
"fields" : [
{
"title" : "Name",
"value" : "ABC"
},
{
"title" : "Gender",
"value" : "Female"
},
{
"title" : "DOB",
"value" : "2010-03-03T18:30:00.000Z"
},
{
"title" : "Email",
"value" : "sample@sample.com"
},
{
"title" : "Work",
"value" : [
"Business"
]
},
{
"title" : "Address",
"value" : "new add"
}
]
},
{
"fields" : [
{
"title" : "FirstJob",
"value" : "new"
},
{
"title" : "Achievments",
"value" : "abc"
}
]
}
]
}
]
}
{
"_id" : NumberInt(6),
"categories" : [
{
"sections" : [
{
"fields" : [
{
"title" : "Name",
"value" : "Sample"
},
{
"title" : "Gender",
"value" : "Male"
},
{
"title" : "DOB",
"value" : "2018-10-22T18:30:00.000Z"
},
{
"title" : "Email",
"value" : "o@o.com"
},
{
"title" : "Work",
"value" : [
"Freelancer"
]
},
{
"title" : "Address",
"value" : "old add"
}
]
},
{
"fields" : [
{
"title" : "FirstJob",
"value" : "ddds"
},
{
"title" : "Achievments",
"value" : "dsdsds"
}
]
}
]
}
]
}
我想使用mongo查询或pymongo查找每个ID的电子邮件及其价值和成就及其价值
预期产量
{
"_id" : NumberInt(6),
"categories" : [
{
"sections" : [
{
"fields" : [
{
"Email", : "o@o.com"
}
]
},
{
"fields" : [
{
"Achievments" : "dsdsds"
}
]
}
]
}
]
}
我尝试了对象进行数组排列但它不是动态的
db.collections.aggregate(
{ $arrayToObject: { "$literal": [
{ "categories.sections.fields.title": "email", "categories.sections.fields.value": "sample@sample.com"}
] } }
)
答案 0 :(得分:0)
使用$ elemMatch,我们可以获取数组的数据。
db.getCollection('transactions').find({"categories.sections.fields": {
"$elemMatch": {
"$and": [
{
"title": { "$eq": "Email" }
},
{
"title": { "$eq": "Achievments" }
}
]
}}})