簡體   English   中英

MongoDb:檢索所有高於某列平均值的文檔

[英]MongoDb: Retrieve all documents higher than the average value of a column

我使用這段代碼創建了一個集合。

db.createCollection("item", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["_id", "item_name", "unit_price"],
            properties: {
                _id: {
                    bsonType: "string",
                    description: "must be a string and is required",
                    minLength: 3,
                    maxLength: 5,
                    pattern: "I[0-9]*$"
                },
                item_name: {
                    bsonType: "string",
                    description: "must be a string and is required"
                },
                unit_price: {
                    bsonType: "double"
                }
            }
        }
    },
    validationLevel: "moderate"
})

並且我在 Item 集合中插入了記錄。 現在我想列出“單價”低於所有商品平均價格的商品。 我試過的是

db.item.aggregate([{
    $group: {
        _id: null,
        averageUnitPrice: {
            $avg: "$unit_price"
        }
    }
}])

我曾嘗試使用上面的代碼,但我無法弄清楚如何取這個平均值並使用它來檢索高於 averageUnitPrice 的文檔。 非常感謝任何幫助。! 非常感謝!

所以我終於想通了。 此查詢將給我平均值和小於平均值的項目列表。

db.item.aggregate([{
        $group: {
                _id: null,
                avg_price: {
                    $avg: "$unit_price"
                },
                unit_price: { 
                   "$addToSet": "$unit_price"
                }
        },
    },{
        $project: {
            avg_price: "$avg_price",
            unit_price: {
                $filter: {
                    input: "$unit_price",
                    as: "unit_prices",
                    cond: {
                        $lt: ["$$unit_prices", "$avg_price"]
                    }
                }   
            }
        }
    }
])

暫無
暫無

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

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