如何在 MongoDB 中有条件地显示/隐藏字段
Posted
技术标签:
【中文标题】如何在 MongoDB 中有条件地显示/隐藏字段【英文标题】:How to Show/Hide Fields conditionally in MongoDB 【发布时间】:2021-08-08 06:26:50 【问题描述】:非常感谢您的帮助,当列的值为空时,我正在尝试使用以下查询隐藏列。
错误:
未捕获的异常:错误:命令失败: “好”:0, "errmsg" : "由 :: Unrecognized expression '$OpenDate' 引起的 $project :: 无效", “代码”:168, "codeName" : "InvalidPipelineOperator"
文档:
"_id" : ObjectId("60f113b2211038b4b688c3e8"),
"URN" : 103600,
"LANAME" : "HTOL",
"LA" : 311,
"ESTAB" : 2014,
"LAESTAB" : 3062352,
"School_Name" : "Good Day Infant School",
"Address" :
"Street" : "Lodge Road",
"Locality" : "",
"Address3" : "",
"Town" : "London",
"PostCode" : "CR9 20P"
,
"Status" : "Open",
"OpenDate" : "",
"CloseDate" : "",
"MINORGROUP" : "Maintained school",
"SCHOOLTYPE" : "Community school",
"ISPRIMARY" : 1,
"ISSECONDARY" : 0,
"ISPOST16" : 0,
"AGELOW" : 3,
"AGEHIGH" : 7,
"GENDER" : "Mixed",
"RELCHAR" : "Does not apply",
"ADMPOL" : "Not applicable"
查询 1:
db.schools.aggregate(
[
$project:
OpenDate:$cond:if:$eq:["$OpenDate",""],then:0,else:1
]
)
查询 2:
db.schools.aggregate(
[
$project:
OpenDate: $cond:["$OpenDate":"",0,1]
]
)
【问题讨论】:
看$cond的正确语法,你的实现无效。 看看这是否有用meta.stackexchange.com/questions/5234/… 【参考方案1】:你可以使用$$REMOVE
db.collection.aggregate([
$project:
OpenDate:
$cond: [
$eq: [
"$OpenDate",
""
]
,
"$$REMOVE",
"$OpenDate"
]
])
工作Mongo playground
【讨论】:
以上是关于如何在 MongoDB 中有条件地显示/隐藏字段的主要内容,如果未能解决你的问题,请参考以下文章