嵌入式数组中的嵌入式文档中的项目字段 [英] Project field in embedded document within embedded array

查看:73
本文介绍了嵌入式数组中的嵌入式文档中的项目字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

 cursor=self.postCol.aggregate([
      { "$graphLookup" : {
        "from": "pCol",
        "startWith": "$parent",
        "connectFromField": "parent",
        "connectToField": "_id",
        "as" : "parents"
        }
      },
      { "$project" : {
         "pValue": {
             "$cond": [
               { "$ne": [ "$pValue", [] ] },
               "$pValue",
               "$parents.0.pValue"
             ]
           }
         }
      }
    ])

先给出以下记录:

{"_id": 4, parent: "", "pValue": ["d"], fieldA: 9},
{"_id": 5, parent: 4, "pValue": [], fieldA:2},
{"_id": 6, parent: 4,"pValue": [], fieldA: 9}

我应该得到:

{"_id": 4, "pValue": ["d"]}
{"_id": 5, "pValue": ["d"]}
{"_id": 6, "pValue": ["d"]}

相反,我得到了:

{"_id": 4, "pValue": ["d"]}
{"_id": 5, "pValue": []}
{"_id": 6, "pValue": []}

由于某些我不理解的原因,$parents.0.pValue没有返回正确的值.如何在Parents数组的第一个元素中选择pValue的字段?

The $parents.0.pValue isn't returning the right value for some reason which I don't understand. How can I select the field of pValue within the first element of the parents array?

我想使用{"$arrayElemAt": ["$parents",0]}它将为我提供嵌入式文档,但是然后如何从中获取要返回的字段?

I thought to use {"$arrayElemAt": ["$parents",0]} which will give me the embedded document but then how can I then get a field from that to be returned?

推荐答案

您可以使用$let运算符在下面替换else条件.

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

 {
    $let: {
        vars: {
            obj: {
                "$arrayElemAt": ["$parents", 0]
            }
        },
        in: "$$obj.pValue"
    }
 }

这篇关于嵌入式数组中的嵌入式文档中的项目字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆