如何在 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 } }
廣告
資料結構
網路技術
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP