首页 > 解决方案 > 如何在 MongoDB 中使用正则表达式访问数组中的数组

问题描述

所以我想从规范中访问值并过滤掉具有所需值的变体。 产品架构

({
    title: { type: String },
    brandName : { type : String },
    ratings : { type: Number, default : 0 },
    specification: [{
        attribute: { type : String },
        values: [{ type : String }],
    }],
    variant: [{
        specifications: [{
            attribute: { type : String },
            values: { type : String }
        }],
    }],
});

我想根据请求的参数过滤掉产品。

过滤对象

{
  "title": "string",
  "brandName": "string",
  "ratings": 0,
  "color": [
    "string"
  ],
  "seat": [
    "string"
  ]
}

这是我的过滤器对象,我将此对象传递给一个函数,然后在数据库中查找它。

过滤功能

public async getAllProducts(param){
        const skip = (page - 1) * limit;
        const users = (await this.productModel
            .find(
                {
                    $or: [
                        {
                            title : param.title
                        },
                        {
                            brandName : param.brandName
                        },
                        {
                            ratings: param.ratings
                        },
                        {
                            "variant.specifications.values" : {"$in": param.color }
                        },
                        {
                            "variant.specifications.values" : {"$in" : param.seat }
                        }
                    ]
                }
            )
            .limit(limit)
            .skip(skip)
        return users;
    }

在这里,我尝试传入 Filter Obj 并使用 $in 运算符来检查 Filter Obj 的颜色和座位数组中的每个值。它会正确地向我返回带有标题、品牌名称和评级的产品,但它不适用于颜色和座椅阵列。

标签: mongodbmongodb-queryaggregation-framework

解决方案


推荐阅读