새 필드를 추가하려면 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 " }