英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论