Access the inner element after an expression

Viewed 19

I want to access the nested object after an expression. In a usual case, this would be done with "$thing.subthing". I have an expression that will resolve into $thing but I want to access subthing in the same line. My code for this:

[
  {"$project":
    {
      "refAgentId":true,"_id":false
    }
  },
  {
    "$lookup":
    {
      "from":"policyTransactions",
      "let":{"refAgentId":"$refAgentId"},
      "pipeline":[],
      "as":"bind"
    }
  },
  {
    "$project":{
      "refAgentId":true,
      "binding":{
       "$arrayElemAt":[{
        "$filter":{
         "input":"$bind",
         "as":"a",
         "cond":{
          "$eq":[
           "$refAgentId",
           "$$a.refAgentId"]}}},
       0]}
    }
  }

]

After all that, I would get the result

{
   "refAgentId": "d6ae049b-edb6-4e55-b3d3-ae994d02fd02",
   "binding": {
     "bind": 35,
     "refAgentId": "d6ae049b-edb6-4e55-b3d3-ae994d02fd02"
   }
}

I want binding to be the 35. I could do this with another project and "binding.bind", but I want to know if it's possible without.

1 Answers

It's not clear what your entire data model is, but here's one way to produce the output you seem to want.

N.B.: This assumes there's a one-to-one relationship between "refAgentId" and an entry in the "policyTransactions" collection. If more than one "policyTransaction" can be associated with an "agentId", then most likely the "$project" will need to be expanded, or possibly even the addition of a "pipeline" in the "$lookup". There's always more than one way to do it.

db.refAgents.aggregate([
  {
    "$lookup": {
      "from": "policyTransactions",
      "localField": "refAgentId",
      "foreignField": "refAgentId",
      "as": "bind"
    }
  },
  {
    "$project": {
      "_id": 0,
      "refAgentId": 1,
      "binding": {
        "$first": "$bind.bind"
      }
    }
  }
])

Try it on mongoplayground.net.

Related