如何在mongodb中编写一个查询,其中键存在于多个位置的对象中的一个对象中



样本数据:

{
"identifier": "1",
"family": "accessories",
"parent": null,
"groups": [],
"categories": [
"A",
"B",
"C"
],
"enabled": true,
"value": {
"name": [
{
"locale": null,
"scope": null,
"data": "TV"
}
],
"customText": [
{
"locale": "de_DE",
"scope": "ecommerce",
"data": "ABC"
},
{
"locale": "en_US",
"scope": "ecommerce",
"data": "BCD"
},
{
"locale": "fr_FR",
"scope": "ecommerce",
"data": "ASD"
}
],
"newAttribute": [
{
"locale": "de_DE",
"scope": null,
"data": "asdasd"
},
{
"locale": "en_US",
"scope": null,
"data": "asd"
},
{
"locale": "fr_FR",
"scope": null,
"data": "awd"
}
],
"release_date": [
{
"locale": null,
"scope": "ecommerce",
"data": "2012-03-29T00:00:00+00:00"
}
],
"targetLocales": [
{
"locale": null,
"scope": null,
"data": [
"fr_FR"
]
}
]
}
}

这是我的示例数据,其中有多个具有value属性的文档。并且我想找到所有那些locale="0"的结果;de_de";。但我无法提出一个问题。我是这个mongoDB的新手,我能想到的就是:

collection.find( $elemMatch : { value.name.locale : "de_DE" }, $elemMatch : { value.customText.locale : "de_DE" }, ...)

这显然不是一种优化的方式。有人能帮我吗?

您可以使用$或子句并传入所有要匹配的表达式。

const localName = "de_DE";
YourCollection.find({
$or: [
{
"value.name.locale": localName 
},
{
"value.customText.locale": localName 
},
{
"value.newAttribute.locale": localName 
},
// repeat for the rest of the fields
]
});

以下是mongoplayground上的一个示例:https://mongoplayground.net/p/5YAJQvWjMJq

如果您只想在以上所有字段都包含"de_DE"的情况下匹配文档,您可以简单地将$or交换为$and

最新更新