【问题标题】:Remove a particular field for all documents in a collection using aggregation in mongoDB使用 mongoDB 中的聚合删除集合中所有文档的特定字段
【发布时间】:2020-09-03 05:39:06
【问题描述】:

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

收集数据:

[
 {
    _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

【问题讨论】:

    标签: mongodb aggregation-framework aggregate aggregate-functions aggregation


    【解决方案1】:

    你可以使用$$REMOVEas 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

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2021-02-19
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多