我正在使用 MongoDB 中的聚合方法查詢資料,但是我遇到了問題。具體來說,我想用大于0的欄位的第一項中的欄位值替換price欄位的值(條件:如果該欄位值為null)。我該怎么做?price_optionmodelstock_count
我用聚合查詢集合的代碼:
const doc = await ProductModel.aggregate([
...
{
$group: {
_id: '$_id',
price: { $first: "$price" },
model: {
$addToSet: {
price_option: '$model.priceOption',
currency_unit: '$model.currencyUnit',
stock_count: '$model.stockCount'
}
}
}
},
{
$project: {
_id: 0,
id: '$_id',
price: 1,
model: 1
}
}
])
我在集合中創建的示例資料:
{
"price": null,
"model": [
{
"price_option": "200",
"currency_unit": "dollar",
"stock_count": 5
},
{
"price_option": "350",
"currency_unit": "dollar",
"stock_count": 0
},
{
"price_option": "400",
"currency_unit": "dollar",
"stock_count": 2
},
]
}
]
我想要的輸出是:
{
"price": "200", <= it would be replace by the first item of remaining items where stock_count greater than 0
"model": [
{
"price_option": "200",
"currency_unit": "dollar",
"stock_count": 5
},
{
"price_option": "350",
"currency_unit": "dollar",
"stock_count": 0
},
{
"price_option": "400",
"currency_unit": "dollar",
"stock_count": 2
},
]
}
uj5u.com熱心網友回復:
$set- 創建price_model欄位。1.1。
$filter過濾model陣列中包含stock_count$get0 的檔案。1.2.
first從 1.1 的結果中獲取第一個檔案。$project- 裝飾輸出檔案。用分配price欄位price_model.price_option。
db.collection.aggregate([
{
$set: {
price_model: {
$first: {
"$filter": {
"input": "$model",
"cond": {
$gt: [
"$$this.stock_count",
0
]
}
}
}
}
}
},
{
$project: {
_id: 0,
id: "$_id",
price: "$price_model.price_option",
model: 1
}
}
])
示例 Mongo Playground
對于 MongoDB 4.2 版,您可以使用$arrayElementAt來獲取陣列的第一個元素。
db.collection.aggregate([
{
$set: {
price_model: {
$arrayElemAt: [
{
"$filter": {
"input": "$model",
"cond": {
$gt: [
"$$this.stock_count",
0
]
}
}
},
0
]
}
}
},
{
$project: {
_id: 0,
id: "$_id",
price: "$price_model.price_option",
model: 1
}
}
])
示例 Mongo Playground ( $arrayElementAt)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430448.html
