给定嵌套文档的 MongoDB 查询

问题描述 投票:0回答:1

这里我只显示了单个文档,但数组有多个文档,我想获取所有内部存储(内存 -> 内部)为 128GB 的文档

数据:

[
    {
        "_id": "654686dc65bc1013eae01dad",
        "name": "Samsung Galaxy Tab A9+",
        "detailSpec": [
            {
                "category": "Network",
                "specifications": [
                    {
                        "name": "Technology",
                        "value": "GSM / HSPA / LTE / 5G",
                        "_id": "654686dc65bc1013eae01daf"
                    },
                    {
                        "name": "2G bands",
                        "value": "GSM 850 / 900 / 1800 / 1900 ",
                        "_id": "654686dc65bc1013eae01db0"
                    }
                ],
                "_id": "654686dc65bc1013eae01dae"
            },
            {
                "category": "Memory",
                "specifications": [
                    {
                        "name": "Card slot",
                        "value": "microSDXC (dedicated slot)",
                        "_id": "654686dc65bc1013eae01dc6"
                    },
                    {
                        "name": "Internal",
                        "value": "64GB 4GB RAM, 128GB 8GB RAM",
                        "_id": "654686dc65bc1013eae01dc7"
                    }
                ],
                "_id": "654686dc65bc1013eae01dc5"
            },
        ],
        "quickSpec": [
            {
                "name": "Display size",
                "value": "11.0\"",
                "_id": "654686dc65bc1013eae01de2"
            }
        ],
        "__v": 0
    }
]

我已经尝试过这个查询,但问题是,它正在考虑所有类别的值字段,但我只想考虑“内存”类别,然后仅检查“内存”类别内的值字段:

const filteredData = await Models.devices.find({
        $and: [
            {
                $and: [
                    {"detailSpec.category": "Memory"},
                    {"detailSpec.specifications.name": "Internal"},
                    {"detailSpec.specifications.value": new RegExp(informationAboutFilter.storage) }
                ]
            }
        ]
    })
console.log(new RegExp(informationAboutFilter.storage))
Output: /128/
mongodb mongoose mongodb-query nested-documents
1个回答
0
投票

您可以使用 $elemMatch 仅匹配

detailSpec
数组中的对象。然后,您可以在投影对象中使用 位置运算符
$
,因为:

位置 $ 运算符限制数组的内容以返回数组上与查询条件匹配的第一个元素。当您只需要选定文档中的一个特定数组元素时,请在 find() 方法或 findOne() 方法的投影文档中使用 $ 。

将您的查询更改为:

const filteredData = await Models.devices.find({
  detailSpec: {
    $elemMatch: {
      category: "Memory",
      "specifications.name": "Internal",
      "specifications.value": {
        "$regex": informationAboutFilter.storage
      }
    }
  }
},
{
  "detailSpec.$": 1
})

请参阅此处了解工作示例。您会注意到

"$regex": "128"
的使用,因为
new RegExp
函数在 mongoplayground 上不可用,但它们是等效的。

© www.soinside.com 2019 - 2024. All rights reserved.