问题
Why $expr is not supported inside $elemMatch? Currently its throwing error as "$expr can only be applied to the top-level document". I can't see any logical reason for this and also what is the optimal way to achieve the same? Please find the sample query.
[ 
   { 
      "$lookup":{ 
         "localField":"id",
         "from":"agents",
         "foreignField":"lead_id",
         "as":"agents"
      }
   },
   { 
      "$match":{ 
         "assignment_supply_entity_mapping_id":{ 
            "$in":[ 
               1199
            ]
         },
         "agents":{ 
            "$elemMatch":{ 
               "id":{ 
                  "$in":[ 
                     699
                  ]
               },
               "$and":[ 
                  { 
                     "status_timestamps.failed_timestamp":{ 
                        "$exists":true
                     }
                  },
                  { 
                     "$or":[ 
                        { 
                           "status_timestamps.junk_timestamp":{ 
                              "$exists":false
                           }
                        },
                        { 
                           "$and":[ 
                              { 
                                 "status_timestamps.junk_timestamp":{ 
                                    "$exists":true
                                 }
                              },
                              { 
                                 "$expr":{ 
                                    "$lt":[ 
                                     "$status_timestamps.failed_timestamp",
                                       "$status_timestamps.junk_timestamp"
                                    ]
                                 }
                              }
                           ]
                        }
                     ]
                  }
               ]
            }
         }
      }
   },
   { 
      "$project":{ 
         "_id":1
      }
   },
   { 
      "$group":{ 
         "count":{ 
            "$sum":1
         },
         "_id":null
      }
   }
]
    回答1:
Perhaps add a helper field?
 { 
      "$lookup":{ 
         "localField":"id",
         "from":"agents",
         "foreignField":"lead_id",
         "as":"agents"
      }
   },
   {$addFields: { XX: {$lt: ["$status_timestamps.failed_timestamp",
                        "$status_timestamps.junk_timestamp"] } }} ,
   { 
      "$match":{ 
...
and later
 { 
                           "$and":[ 
                              { 
                                 "status_timestamps.junk_timestamp":{ 
                                    "$exists":true
                                 }
                              },
                              {  "XX": true }
    来源:https://stackoverflow.com/questions/59069229/expr-with-elemmatch-in-mongod