如何在 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 } }

更新于:2020 年 4 月 6 日

451 次观看

开启你的 职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.