Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将mongodb$lookup与嵌套数组一起使用?_Mongodb_Aggregation Framework - Fatal编程技术网

如何将mongodb$lookup与嵌套数组一起使用?

如何将mongodb$lookup与嵌套数组一起使用?,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我正在尝试执行一个搜索查询,它将合并两个集合 集合1称为库存集合 { "fruit_id" : "1", "name" : "apples", "stock": 100 } { "fruit_id" : "2", "name" : "oranges", "stock": 50 } { "fruit_id" : "3", "name" : "plums", "stock": 60 } 集合2称为订单集合 { "order_id" : "001", "ordered_fruits": [

我正在尝试执行一个搜索查询,它将合并两个集合

集合1称为库存集合

{ "fruit_id" : "1", "name" : "apples", "stock": 100 }
{ "fruit_id" : "2", "name" : "oranges", "stock": 50 }
{ "fruit_id" : "3", "name" : "plums", "stock": 60 } 
集合2称为
订单
集合

{ "order_id" : "001", "ordered_fruits":
    [
     {"fruit_id" : "1", "name" : "apples", "ordered" : 5},
     {"fruit_id" : "3", "name" : "plums", "ordered" : 20}
    ]
}
{ "order_id" : "002", "ordered_fruits":
    [
     {"fruit_id" : "2", "name" : "oranges", "ordered" : 30},
     {"fruit_id" : "3", "name" : "plums", "ordered" : 20}
    ]
}
我正在尝试编写一个查询代码,该查询返回stock集合,其中包含一个表示已订购水果总量的额外密钥对

{ "fruit_id" : "1", "name" : "apples", "stock": 100, "ordered": 5 }
{ "fruit_id" : "2", "name" : "oranges", "stock": 50, "ordered": 30 }
{ "fruit_id" : "3", "name" : "plums", "stock": 60, "ordered": 40 }

我曾尝试使用聚合框架中的$lookup,但嵌套数组会使它变得复杂。我现在被卡住了。

你可以使用下面的聚合

db.stock.aggregate([
  { "$lookup": {
    "from": "orders",
    "let": { "fruitId": "$fruit_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$fruitId", "$ordered_fruits.fruit_id"] }}},
      { "$unwind": "$ordered_fruits" },
      { "$match": { "$expr": { "$eq": ["$ordered_fruits.fruit_id", "$$fruitId"] }}}
    ],
    "as": "orders"
  }},
  { "$project": {
    "ordered": { "$sum": "$orders.ordered_fruits.ordered" },
    "fruit_id" : 1, "name" : 1, "stock": 1
  }}
])

工作得很好!