添加新字段和连接除以特定数字的价格结果的 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