MongoDB:投影到 return 只是嵌套到另一个嵌套到对象的数组的数组的第一个元素

MongoDB: Make a projection to return just the first element of an array nested to another array nested to an object

我有以下内容:我需要使用 return 只是列表的第一个元素的投影从 MongoDB 检索文档。但是,这个列表在另一个列表中,而这个列表在一个对象中,而这个对象又在文档中的另一个对象中。看起来像下面这样:

{
  "items": {
    "item": [
      {
        "items": {
          "item": [
            {
              "cell": [
                {
                  "value": "a"
                },
                {
                  "value": "b"
                },
                {
                  "value": "c"
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

我的目标是通过 value 获取它:"a" 使用投影来避免其他值。也就是说,我的投影应该return这个:

{
  "items": {
    "item": [
      {
        "items": {
          "item": [
            {
              "cell": [
                {
                  "value": "a"
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

问题是我已经尝试了我所知道的一切:我已经将 $elemMatch、$ 和 $slice 用于 return 只是第一个元素,但我无法进行查询来执行此操作因为文件的复杂性。我正在使用 MongoDB 3.2.

如果您需要更多信息,我会在这里更新。总之,谢谢大家!

您可以试试下面的方法。使用 $map operators to reach to the cell array while keeping the structure and uses $slice 选择第一个值。

aggregate({
    $project: {
        items: {
            item: {
                $map: {
                    input: "$items.item",
                    as: "outer",
                    in: {
                        "items": {
                            item: {
                                $map: {
                                    input: "$$outer.items.item",
                                    as: "inner",
                                    in: {
                                        "cell": {
                                            $slice: ["$$inner.cell", 1]
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        _id: 0
    }
})