所谓数组交集,指的是库存元素数量远多于每个文档原料数组的情况下,希望从查询结果中获得所有数组元素均包含在库存中的文档。即使所有原料都包含在库存中,$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" ]
使用此库存数组,我想获取食谱2和食谱3。
目前我有这个库存数组和查询(感谢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" ]
...
}
但我没有得到任何结果
$all
选项更新了问题,但我不确定您所说的数组交集是什么意思,能否解释一下? - turivishal