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

Remove a particular field for all documents in a collection using aggregation in mongoDB

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

收集数据:

[
 {
    _id: "bmasndvhjbcw",
    name: "lucas",
    occupation: "scientist",
    present_working:true,
    age: 55,
    location: "texas"

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

删除记录中有 present_working:false 的行。数据不需要在数据库中移除,应该只在聚合管道中修改

仅删除 present_working:falsepresent_working:false 后的预期输出应保留在数据库中。 :

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

MongoDB版本:4.0

您可以使用 $$REMOVE as part of $project:

db.collection.aggregate([
    {
        $project: {
            _id: 1,
            name: 1,
            occupation: 1,
            age: 1,
            location: 1,
            present_working: { $cond: [ { $eq: [ "$present_working", false ] }, "$$REMOVE", "$present_working" ] }
        }
    }
])

Mongo Playground