从子文档数组中的数组中查找具有特定值的文档

时间:2020-07-18 08:42:52

标签: javascript mongodb

我想查找在子文档数组中具有与另一个数组中的任何内容匹配的值的所有文档。

文档

{
    storeName: String,
    location: String,
    inventory: [{
        itemName: String,
        price: Number,
        otherDetail: String,
    }]
}

示例数组

let itemNames = ["chair", "bed", "table"];

我正在使用聚合。我需要找到清单中具有数组中任何itemNames的所有商店(文档)。

1 个答案:

答案 0 :(得分:1)

结合使用$elemMatch运算符和$in来过滤嵌套数组。

var filter = {
    inventory: {
        $elemMatch: {
            itemName: {
                $in: ["chair", "bed", "table"]
            }
        }
    }
};

db.collection.find(filter);

使用aggregate-

var pipeline = [
    {
        $match: {
            inventory: {
                $elemMatch: {
                    itemName: {
                        $in: ["chair", "bed", "table"]
                    }
                }
            }
        }
    }
];

db.collection.aggregate(pipeline);
相关问题