Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB의 문서 필드 값에서 값(TotalPrice – Discount)을 빼는 방법은 무엇입니까?


문서 필드 값에서 값을 빼려면 MongoDB 집계()에서 $subtract를 사용합니다. 문서로 컬렉션을 만들자 −

> db.demo599.insertOne({"TotalPrice":250,"DiscountPrice":35});{ "승인됨" :true, "insertedId" :ObjectId("5e948192f5f1e70e134e2696")}> db.insertOne {"TotalPrice":400,"DiscountPrice":10});{ "acknowledged":true, "insertedId":ObjectId("5e948199f5f1e70e134e2697")}> db.demo599.insertOne({"TotalPrice","::50});{ "승인됨" :true, "insertedId" :ObjectId("5e9481a0f5f1e70e134e2698")}

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

> db.demo599.find();

이것은 다음과 같은 출력을 생성합니다 -

{ "_id" :ObjectId("5e948192f5f1e70e134e2696"), "TotalPrice" :250, "DiscountPrice" :35 }{ "_id" :ObjectId("5e948199f5f1e70e970e134e2") }{ "_id":ObjectId("5e9481a0f5f1e70e134e2698"), "TotalPrice":1550, "DiscountPrice":50 }

다음은 문서 필드 값에서 값을 빼는 쿼리입니다 -

> db.demo599.aggregate( [ { $project:{ActualPrice:{ $subtract:[ "$TotalPrice", "$DiscountPrice" ] } } } ] )

이것은 다음과 같은 출력을 생성합니다 -

<"_id" :ObjectId("5e948192f5f1e70e134e2696"), "ActualPrice" :215 }{ "_id" :ObjectId("5e948199f5f5f1e70e134e2697"), "39Price" , "실제 가격" :1500 }