Node.js 如何在mongo DB中编写查询,其中键存在于多个位置的对象的对象中?
样本数据:Node.js 如何在mongo DB中编写查询,其中键存在于多个位置的对象的对象中?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,样本数据: { "identifier": "1", "family": "accessories", "parent": null, "groups": [], "categories": [ "A", "B", "C" ], "enabled": true,
{
"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=“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上的一个示例:
如果您只想在上述所有字段都包含“de_de”
的情况下匹配文档,则只需将$或交换为$和