gpt4 book ai didi

mongodb - 如何对 MongoDB 集合中的对象进行分组

转载 作者:行者123 更新时间:2023-12-02 04:16:24 25 4
gpt4 key购买 nike

我有这样的文档集合

{ "owner": "550511223", "file_name": "55234OT01", "file_type": "other", "comment": "Just fix it"},
{ "owner": "550510584", "file_name": "55584RS01", "file_type": "resume", "comment": "Good enough"},
{ "owner": "550511223", "file_name": "55234AP01", "file_type": "applicant", "comment": "This will do"}

我需要一个像这样的对象的结果

{
[{
"owner" : "550510584",
"files" : [{"file_name": "55584RS01","file_type": "resume","comment": "Good enough"}],
},{
"owner" : "550511234",
"files" : [{"file_name": "55234AP01","file_type": "applicant","comment": "This will do"},
{"file_name": "55234OT01","file_type": "other","comment": "Just fix it"}]
}]
}

我正在寻找一种方法来做到这一点。我尝试过分组和聚合,但我只能将 file_name 字段插入,因为我弄乱了语法

最佳答案

您需要$group您的文档由“所有者”创建,然后使用 $push累加器运算符返回文件数组。

db.collection.aggregate([
{ "$group": {
"_id": "$owner",
"files": {
"$push": {
"file_name": "$file_name",
"file_type": "$file_type",
"comment": "$comment"
}
}
} }
])

返回结果:

{
"_id" : "550510584",
"files" : [
{
"file_name" : "55584RS01",
"file_type" : "resume",
"comment" : "Good enough"
}
]
},

{
"_id" : "550511223",
"files" : [
{
"file_name" : "55234OT01",
"file_type" : "other",
"comment" : "Just fix it"
},
{
"file_name" : "55234AP01",
"file_type" : "applicant",
"comment" : "This will do"
}
]
}

关于mongodb - 如何对 MongoDB 集合中的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33466221/

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