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

MongoDB에서 한 컬렉션의 필드가 다른 컬렉션보다 큰 두 컬렉션을 집계하는 방법은 무엇입니까?

<시간/>

이를 위해 $lookup을 사용할 수 있습니다. 문서로 컬렉션을 만들자 −

> db.demo446.insert([
...    { "ProductName": "Product1", "ProductPrice": 60 },
...    { "ProductName": "Product2", "ProductPrice": 90 }
... ])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

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

> db.demo446.find();

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

{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60 }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90 }

다음은 문서로 두 번째 컬렉션을 생성하는 쿼리입니다 -

> db.demo447.insert([
...
...    { "ProductName": "Product1", "ProductPrice": 40 },
...    { "ProductName": "Product2", "ProductPrice": 70 }
... ])
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 2,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})

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

> db.demo447.find();

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

{ "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 }
{ "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 }

다음은 한 컬렉션의 필드가 다른 컬렉션보다 큰 두 컬렉션을 집계하는 쿼리입니다. -

> var rate = 1;
> db.demo446.aggregate([
... { "$match": { "ProductPrice": { "$exists": true }, "ProductName": { "$exists": true } } },
... {
...    "$lookup": {
...       "from": "demo447",
...       "localField": "ProductName",
...       "foreignField": "ProductName",
...       "as": "demo447"
...    }
... },
... { "$unwind": "$demo447" },
... {
...    "$redact": {
...       "$cond": [
...          {
...             "$gt": [
...                "$ProductPrice", {
...                   "$add": [
...                         { "$multiply": [ "$demo447.ProductPrice",rate ] },
...                         3
...                      ]
...                   }
...                ]
...             },
...             "$$KEEP",
...             "$$PRUNE"
...          ]
...       }
...    }
... ])

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

{ "_id" : ObjectId("5e790766bbc41e36cc3caec3"), "ProductName" : "Product1", "ProductPrice" : 60, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec5"), "ProductName" : "Product1", "ProductPrice" : 40 } }
{ "_id" : ObjectId("5e790766bbc41e36cc3caec4"), "ProductName" : "Product2", "ProductPrice" : 90, "demo447" : { "_id" : ObjectId("5e790789bbc41e36cc3caec6"), "ProductName" : "Product2", "ProductPrice" : 70 } }