布尔值到字符串的聚合更改值
Posted
技术标签:
【中文标题】布尔值到字符串的聚合更改值【英文标题】:Aggregation change value of a boolean to string 【发布时间】:2020-07-03 20:02:21 【问题描述】:有一个包含记录的集合,需要将列的布尔值转换为字符串:
[
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
passed_phd: true,
age: 55,
location: "texas",
,
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
passed_phd: true,
location: "texas",
,
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
passed_phd: false,
location: "texas",
,
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
passed_phd: false,
location: "texas"
]
如何将记录的布尔值更改为字符串。
passed_phd 中具有 true(boolean) 的值应转换为 "yes"(string)
passed_phd 中包含 false(boolean) 的值应转换为“no”(string)
[
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
passed_phd: "yes",
age: 55,
location: "texas",
,
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
passed_phd: "yes",
location: "texas",
,
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
passed_phd: "no",
location: "texas",
,
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
passed_phd: "no",
location: "texas"
]
mongodb 4.0 版 .
【问题讨论】:
【参考方案1】:$cond 聚合管道运算符可以做到这一点。
从 MongoDB 4.2 开始,这些可用于更新或聚合管道,例如:
db.collection.aggregate([
$set:
passed_phd:
$cond:
if:"$passed_phd",
then:"yes",
else:"no"
])
【讨论】:
不,聚合不会更新原始文档。如果您希望在不更改原始输出的情况下修改输出,可以在聚合管道中使用$set
阶段。
我只需要修改输出,不需要更新文档。
$set
对象是一个聚合阶段,您可以将其放入现有管道中。
试过这个'$passed_phd':true,$set:'$passed_phd':"yes"
得到这个错误,passed_phd不能以'或$开头
让我们continue this discussion in chat。以上是关于布尔值到字符串的聚合更改值的主要内容,如果未能解决你的问题,请参考以下文章
Pandas映射(转化)dataframe中的布尔值True和False值到1和0数值使用replace函数