我想查找在子文档数组中具有与另一个数组中的任何内容匹配的值的所有文档。
文档
{
storeName: String,
location: String,
inventory: [{
itemName: String,
price: Number,
otherDetail: String,
}]
}
示例数组
let itemNames = ["chair", "bed", "table"];
我正在使用聚合。我需要找到清单中具有数组中任何itemNames的所有商店(文档)。
答案 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);