如何将一个字段添加到基于同一集合中一个字段的蒙哥达集合中?

发布于 2025-02-11 18:58:29 字数 339 浏览 0 评论 0原文

如何根据同一集合中的字段将字段添加到MongoDB集合中?例如,在此集合中:

{"_id" : "Apple", "colour": "green"}
{"_id" : "Apple", "colour": "red"}

我想在“ iSgreen”集合中添加第三个字段,所以看起来像这样:

{"_id" : "Apple", "colour" : "green", "isGreen" : "yes"}
{"_id" : "Apple", "colour" : "red", "isGreen" : "no"}

通过聚合可以做到这一点?

How can I add a field to a MongoDB collection based on a field in the same collection? For example, in this Collection:

{"_id" : "Apple", "colour": "green"}
{"_id" : "Apple", "colour": "red"}

I would like to add a third field in the collection "isGreen" so it would look like this:

{"_id" : "Apple", "colour" : "green", "isGreen" : "yes"}
{"_id" : "Apple", "colour" : "red", "isGreen" : "no"}

Is this possible with an aggregation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴随着你 2025-02-18 18:58:29

使用$ set带有$ cond操作员的阶段。

db.collection.aggregate([
  {
    $set: {
      "isGreen": {
        $cond: {
          if: {
            $eq: [
              "$colour",
              "green"
            ]
          },
          then: "yes",
          else: "no"
        }
      }
    }
  }
])

示例mongo playground

Use $set stage with $cond operator.

db.collection.aggregate([
  {
    $set: {
      "isGreen": {
        $cond: {
          if: {
            $eq: [
              "$colour",
              "green"
            ]
          },
          then: "yes",
          else: "no"
        }
      }
    }
  }
])

Sample Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文