【发布时间】:2021-05-29 16:09:30
【问题描述】:
数组交集的意思是,库存的元素比每个文档成分数组要多得多,我想从查询中得到的结果是所有数组元素都包含在库存中的所有文档。 $all 将使我得到零结果,因为即使在库存中找到所有成分,库存中的元素也比成分中的要多,
我有数以千计的文档具有字符串数组字段
{
...
recipe: "recipe1",
ingredients: [ "1 cup cooked quinoa", "6 tbsp butter", "1 large egg" ]
...
},
{
...
recipe: "recipe2",
ingredients: [ "2 lemons", "2 tbsp butter", "1 large egg" ]
...
}
{
...
recipe: "recipe3",
ingredients: [ "1lb salmon", "1 pinch pepper", "4 spears asparagus" ]
...
}
我正在尝试查找所有文档,其中 ingredients 数组中的所有元素都包含在包含大量元素的示例数组中,假设仅包含以下内容:
inventory = [ "lemons", "butter", "egg", "milk", "bread", "salmon", "asparagus", "pepper" ]
有了这个库存数组,我想得到 recipe2 和 recipe3。
现在我有这个库存数组和查询(感谢turivishal):
let inventory = ["lemons", "butter", "egg", "milk", "bread", "salmon", "asparagus", "pepper"];
inventory = inventory.map((i) => new RegExp(i, "i"));
查询:
Recipe.find({
ingredients: { $all: inventory }
})
预期结果:
{
...
recipe: "recipe2",
ingredients: [ "2 lemons", "2 tbsp butter", "1 large egg" ]
...
}
{
...
recipe: "recipe3",
ingredients: [ "1lb salmon", "1 pinch pepper", "4 spears asparagus" ]
...
}
但我得到的结果为零
【问题讨论】:
标签: javascript mongodb mongoose