gpt4 book ai didi

mongodb - 从多个子文档中获取与 mongodb 中的条件匹配的字段

转载 作者:可可西里 更新时间:2023-11-01 10:44:28 27 4
gpt4 key购买 nike

下面是我在 mongodb 中的收藏 -

{
"_id" : ObjectId("50f69176904e1d66affec20d"),
"connections" : [
{
"id" : "50f651a3b58bba7fbec2f222"
},
{
"group" : "Roomies",
"users" : [
{
"id" : "50f651a3b58bba7fbec2f222"
},
{
"id" : "50f651b8b58bba7fbec2f223"
}
]
},
{
"group" : "College",
"users" : [
{
"id" : "50f651b8b58bba7fbec2f223"
},
{
"id" : "50f651a3b58bba7fbec2f222"
}
]
},
{
"group" : "Work",
"users" : [
{
"id" : "50f651a3b58bba7fbec2f222"
}
]
},
],
"email" : "arunko350@gmail.com",
"name" : "Arun"
}

这里我想获取所有存在id = 50f651a3b58bba7fbec2f222的组名。请帮我。我正在浏览 2 天的解决方案。

最佳答案

您可以使用 MongoDB 2.2 的 aggregation framework 来做到这一点.在外壳中:

db.test.aggregate([
// Duplicate the docs, one per connections array element.
{$unwind: '$connections'},
// Only include the docs with the specified user id
{$match: {'connections.users.id': '50f651a3b58bba7fbec2f222'}},
// Bring group out to the only top level field and exclude _id
{$project: {_id: 0, group: '$connections.group'}}
])

输出:

{
"result": [
{
"group": "Roomies"
},
{
"group": "College"
},
{
"group": "Work"
}
],
"ok": 1
}

关于mongodb - 从多个子文档中获取与 mongodb 中的条件匹配的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433575/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com