Project field in embedded document within embedded array

后端 未结 2 493
感动是毒
感动是毒 2021-01-21 15:27

I have the following query:

 cursor=self.postCol.aggregate([
      { \"$graphLookup\" : {
        \"from\": \"pCol\",
        \"startWith\": \"$parent\",
                


        
相关标签:
2条回答
  • 2021-01-21 15:55

    You can replace the else condition with below using $let operator.

     {
        $let: {
            vars: {
                obj: {
                    "$arrayElemAt": ["$parents", 0]
                }
            },
            in: "$$obj.pValue"
        }
     }
    
    0 讨论(0)
  • 2021-01-21 16:20

    You can use the $switch operator and the $let operator to $project your field.

    The $let variable operator let you assign a value to a variable which can be used in the "in" expression as shown in my other answer here.

    With the $switch operator, we can perform very clean case-statement.

    db.postCol.aggregate([
        { "$graphLookup": { 
            "from": "postCol",  
            "startWith": "$parent",  
            "connectFromField": "parent", 
            "connectToField": "_id",   
            "as" : "parents"           
        }}, 
        { "$project": { 
            "pValue": { 
                "$switch": { 
                    "branches": [ 
                        { "case": { "$gt": [ { "$size": "$pValue"}, 0 ] },
                        "then": "$pValue" }
                    ], 
                    "default": { 
                        "$let": { 
                            "vars": { "p": { "$arrayElemAt": [ "$parents", 0 ] }}, 
                            "in": "$$p.pValue" 
                        }
                    }
                }
            }
        }}
    ])
    
    0 讨论(0)
提交回复
热议问题