Project field in embedded document within embedded array

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

I have the following query:

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


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    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" 
                        }
                    }
                }
            }
        }}
    ])
    

提交回复
热议问题