要添加新字段,请使用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", " \n "] } ... } ... } ... } ... }, ... { ... $project: { ... _id: 0, ... Number:1, ... productPriceList:1 ... } ... } ... ])
这将产生以下输出-
{ "Number" : "7374644", "productPriceList" : "100 \n 400 \n " }