新增新欄位和連線除以特定數字的價格結果的 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
" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP