【问题标题】: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 版 .

【问题讨论】:

    标签: mongodb aggregation-framework aggregate aggregation


    【解决方案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不能以'或$开头
    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2019-06-09
    • 2014-12-17
    • 1970-01-01
    相关资源
    最近更新 更多