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