使用 mongoDB 中的聚合删除集合中所有文档的特定字段
Posted
技术标签:
【中文标题】使用 mongoDB 中的聚合删除集合中所有文档的特定字段【英文标题】:Remove a particular field for all documents in a collection using aggregation in 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:false
和 present_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
【问题讨论】:
【参考方案1】:你可以使用$$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
【讨论】:
以上是关于使用 mongoDB 中的聚合删除集合中所有文档的特定字段的主要内容,如果未能解决你的问题,请参考以下文章