使用MongoDB中的聚合来获取特定字段的值

huangapple go评论84阅读模式
英文:

Get value of a specific field using aggregation in MongoDB

问题

[
{
"_id": "5f969419d40c1580f2d4aa36",
"users": {
"foo@bar.com": "baz"
}
},
{
"_id": "5f9694d4d40c1580f2d4aa38",
"users": {
"baz@test.com": "foo"
}
}
]

英文:

My document:

[
  {
    "_id": "5f969419d40c1580f2d4aa36",
    "users": {
      "foo@bar.com": "baz",
      "foo2@bar.com": "baz2"
    }
  },
  {
    "_id": "5f9694d4d40c1580f2d4aa38",
    "users": {
      "baz@test.com": "foo"
    }
  }
]

If i use this aggregate, i get two users. Ok. But how can i get only the value of "foo@bar.com"?
Test in https://mongoplayground.net/p/3kW2Rw6fSjh

db.collection.aggregate([
  {
    "$project": {
      "users": {
        "$objectToArray": "$users"
      }
    }
  },
  {
    "$match": {
      "users.k": "foo@bar.com"
    }
  },
  {
    "$project": {
      "users": {
        "$arrayToObject": "$users"
      }
    }
  }
])

答案1

得分: 1

你可以在$match阶段之后添加一个$filter阶段:

{
    $set: {
      users: {
        $filter: {
          input: "$users",
          cond: {
            $eq: [
              "$$this.k",
              "foo2@bar.com"
            ]
          }
        }
      }
    }
}

playground示例上查看其工作原理。

英文:

You can add a $filter stage after the $match stage:

{
    $set: {
      users: {
        $filter: {
          input: "$users",
          cond: {
            $eq: [
              "$$this.k",
              "foo2@bar.com"
            ]
          }
        }
      }
    }
  },

See how it works on the playground example

huangapple
  • 本文由 发表于 2023年2月9日 00:16:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定