新增新欄位和連線除以特定數字的價格結果的 MongoDB 查詢


要新增新欄位,請在 MongoDB 中使用 $addFields。我們建立一個包含文件的集合 -

> db.demo719.insertOne(
...    {
...       "Number":"7374644",
...       "details" : {
...          "otherDetails" : [
...             {
...                "ProductId" :"102",
...                "ProductPrice" : NumberInt(500)
...             },
...             {
...                "ProductId" :"103",
...                "ProductPrice" : NumberInt(2000)
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eaae56c43417811278f5882")
}

使用 find() 方法顯示來自集合的所有文件 -

> db.demo719.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5eaae56c43417811278f5882"), "Number" : "7374644", "details" : { "otherDetails" : [ { "ProductId" : "102", "ProductPrice" : 500 }, { "ProductId" : "103", "ProductPrice" : 2000 } ] } }

以下是新增新欄位和連線除以特定數字的價格結果的查詢 -

> db.demo719.aggregate([
...    {
...       $addFields:{
...          productPriceList: {
...             $reduce: {
...                input: {
...                   $map: {
...                      input: "$details.otherDetails.ProductPrice",
...                      in: { $toString: { $divide: ["$$this", 5] } }
...                   }
...                },
...                initialValue: "",
...                in: { $concat: ["$$value", "$$this", " 
"] } ...             } ...          } ...       } ...    }, ...    { ...       $project: { ...          _id: 0, ...          Number:1, ...          productPriceList:1 ...       } ...    } ... ])

這將產生以下輸出 -

{ "Number" : "7374644", "productPriceList" : "100 
400
" }

更新於: 2020年5月15日

387 次瀏覽

開啟 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.