首页 > 解决方案 > 删除 pyMongo 列表中的列表条目

问题描述

我有一个数据库集合,其中包含这样的对象:

{
    "_id": ObjectId("something"),
    "name_lower": "total",
    "name": "Total",
    "mounts": [
        [
            "mount1",
            "instance1"
        ],
        [
            "mount2",
            "instance1"
        ],
        [
            "mount1",
            "instance2"
        ],
        [
            "mount2",
            "instance2"
        ]
    ]
}

假设我想删除具有实例 instance2 的每个挂载,我将如何去做?我已经搜索了很长时间。

标签: pythonpython-3.xmongodbpymongopymongo-3.x

解决方案


你可以做这样的事情

[
  {
    $unwind: "$mounts"
  },
  {
    $match: {
      "mounts": {
        $ne: "instance2"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      name: {
        $first: "$name"
      },
      mounts: {
        $push: "$mounts"
      }
    }
  }
]

工作Mongo游乐场


推荐阅读