使用MongoDB聚合删除集合中所有文档的特定字段

时间:2020-04-08 04:10:15

标签: mongodb mongodb-query aggregation-framework

如何使用聚合为集合中的所有记录删除特定值:

具有数据收集:

[
 {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",
    date:2019-11-25T10:49:36.534+00:00

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas",
    date:null
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas",
    date:null
  }
]

删除记录中有date:null的行。无需在数据库中删除数据,而应仅在聚合管道中对其进行修改

仅删除date:null后的预期输出:

[
 {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas",
    date:2019-11-25T10:49:36.534+00:00

  },
  {
    _id: "bmasndvhjbcx",
    name: "mark",
    occupation: "scientist",
    age: 45,
    present_working:true,
    location: "texas"
  },
  {
    _id: "bmasndvhjbcq",
    name: "cooper",
    occupation: "physicist",
    age: 69,
    location: "texas"
  }
]

MongoDB版本: 4.0

1 个答案:

答案 0 :(得分:1)

您可以使用$ifNull运算符和$$REMOVE来做到这一点:

db.collection.aggregate([
  {
    $addFields: {
      date: {
        $ifNull: [
          "$date",
          "$$REMOVE"
        ]
      }
    }
  }
])

测试: MongoDB-Playground