簡體   English   中英

從子文檔數組中的數組中查找具有特定值的文檔

[英]Find document with specific value from array within an array of subdocuments

我想在一個子文檔數組中找到所有具有與另一個數組中的任何內容匹配的值的文檔。

文件

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

示例數組

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

我正在使用聚合。 我需要找到庫存中包含數組中任何 itemNames 的所有商店(文檔)。

使用$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM