Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB切片-从嵌套数组中删除最后n个元素_Mongodb_Mongodb Query_Aggregation Framework_Pymongo - Fatal编程技术网

MongoDB切片-从嵌套数组中删除最后n个元素

MongoDB切片-从嵌套数组中删除最后n个元素,mongodb,mongodb-query,aggregation-framework,pymongo,Mongodb,Mongodb Query,Aggregation Framework,Pymongo,假设我有以下数组: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } 如果我想选择除最后3个之外的所有元素,我可以使用建议的解决方案 我可以获得所需的输出: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0] { data: [[1,

假设我有以下数组:

{
   data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0]
}
如果我想选择除最后3个之外的所有元素,我可以使用建议的解决方案

我可以获得所需的输出:

[1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0]
        {
           data: [[1, 0, 4, 0], [1, 0, 4, 0]]
        }
如何对串联/嵌套数组执行相同的操作,如:

 {
       data: [[1, 0, 4, 0, 0, 4, 1], [1, 0, 4, 0, 1, 5, 3]]
 }
要选择所有元素(每个数组的最后3个元素除外)

预期产出:

[1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0]
        {
           data: [[1, 0, 4, 0], [1, 0, 4, 0]]
        }
您可以使用来迭代数组并执行相同操作:

db.collection.aggregate([
  {
    $addFields: {
      data: {
        $map: {
          input: "$data",
          in: {
            "$slice": [
              "$$this",
              0,
              {
                $subtract: [
                  {
                    $size: "$$this"
                  },
                  3
                ]
              }
            ]
          }
        }
      }
    }
  }
])

测试:

非常感谢