在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 } }热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便