添加限制并跳过聚合函数后,$ lookup不起作用

我是mongodb的新手,我很困惑为什么在下面的情况下查找不起作用

//查找无效

[
   {
      "$match":{
         "is_active":{
            "$eq":1
         }
      }
   },{
      "$facet":{
         "length":[
            {
               "$count":"total"
            }
         ],"data":[
            {
               "$skip":0
            },{
               "$limit":10
            }
         ]
      }
   },{
      "$lookup":{
         "from":"offences","localField":"offences","foreignField":"offence_id","as":"offenceSetail"
      }
   },{
      "$project":{
         "offences.is_active":0
      }
   },{
      "$replaceRoot":{
         "newRoot":{
            "$mergeObjects":[
               {
                  "$arrayElemAt":[
                     "$offenceSetail",0
                  ]
               },"$$ROOT"
            ]
         }
      }
   },{
      "$project":{
         "offenceSetail":0
      }
   },{
      "$lookup":{
         "from":"registers","localField":"user_id","foreignField":"id","as":"sender"
      }
   },{
      "$project":{
         "registers.is_active":0
      }
   },{
      "$replaceRoot":{
         "newRoot":{
            "$mergeObjects":[
               {
                  "$arrayElemAt":[
                     "$sender",{
      "$project":{
         "sender":0
      }
   }
],"options":{

}
}

//查找正常

[
   {
      "$match":{
         "is_active":{
            "$eq":1
         }
      }
   },{
      "$project":{
         "sender":0
      }
   },{
               "$limit":10
            }
         ]
      }
   }
],"options":{

}
}

请帮助我如何解决它。 谢谢

orgjava 回答:添加限制并跳过聚合函数后,$ lookup不起作用

在第一种情况下,查找无效,因为在查找中指定的本地字段不存在。在$facet阶段之后,我们得到两个数组,即lengthdata。我们需要将localField指定为data.offences

,

使用$ facet,您将可以同时运行两个聚合。使用$ facet所获得的每个字段都代表单独的聚合管道,这就是为什么总是获得数组作为输出的原因。

{
  "$facet":{
     "length":[
        {
           "$count":"total"
        }
     ],"data":[
        { "$skip":0 },{ "$limit":10 }
     ]
  }

}

您将获得两个数组,即长度和数据。示例:

{
"length" : [ 
    {
        "total" : 360
    }
],"data" : [ 
    {
        "_id" : ObjectId("5d5beae5662cdb57e2b80eff"),"is_active": 1
    },...
]

}

因此,您必须先$ unwind“数据”。然后执行查找操作。因此,您可以执行以下操作

// After $facet
{
    $unwind: "$data"
},{
      "$lookup":{
         "from":"offences","localField":"data.offences","foreignField":"offence_id","as":"offenceSetail"
      }
 },{
    $unwind: "$offenceSetail"
}
本文链接:https://www.f2er.com/3122558.html

大家都在问