我通过查询从嵌套数组文档中检索唯一的对象数组,所以我在其中使用了聚合和$group。
我的数据结构
{
_id: ObjectId('637b22639356492ae41bbe23'),
studentAgeCategories: [
{
competitionsType: [
{
competitionsTypeId: ObjectId("5fec0c53a534c297c6b4c5c3"),
competitionsTypeName: "Animation/Documentary/Film"
}
]
}
]
}
尝试的查询
{'$match': {'_id': ObjectId('637b22639356492ae41bbe23')}},
{'$unwind': '$studentAgeCategories'},
{'$group': {
'_id': '$studentAgeCategories.competitionsType.competitionsTypeId',
'competitionType': {
'$push': {
'_id': '$studentAgeCategories.competitionsType.competitionsTypeId',
'competitionsTypeName': '$studentAgeCategories.competitionsType.competitionsTypeName'
}
}
}
}
dbconn.clnEvents.aggregate(pipeline)
这就是结果。
/* 1 */
{
"_id" : [
ObjectId("5fec0c53a534c297c6b4c5c3"),
ObjectId("5fec0c65a534c297c6b4ce3a"),
ObjectId("5fec0c8aa534c297c6b4dda7")
],
"competitionType" : [
{
"_id" : [
ObjectId("5fec0c53a534c297c6b4c5c3"),
ObjectId("5fec0c65a534c297c6b4ce3a"),
ObjectId("5fec0c8aa534c297c6b4dda7")
],
"competitionsTypeName" : [ "Animation/Documentary/Film", "Visual coding", "Websites/Web/Mobile Apps" ]
}
]
},
/* 2 */
{
"_id" : [
ObjectId("5ff457b2add6eab7491fff13")
],
"competitionType" : [
{
"_id" : [
ObjectId("5ff457b2add6eab7491fff13")
],
"competitionsTypeName" : [ "Presentation" ]
}
]
},
/* 3 */
{
"_id" : [
ObjectId("5fec0c9fa534c297c6b4e4b6")
],
"competitionType" : [
{
"_id" : [
ObjectId("5fec0c9fa534c297c6b4e4b6")
],
"competitionsTypeName" : [ "AI/Robotics/IoT" ]
}
]
},
/* 4 */
{
"_id" : [
ObjectId("60d8843f6ac43b6179d3bd7e"),
ObjectId("5ff457b2add6eab7491fff13"),
ObjectId("5fec0c53a534c297c6b4c5c3")
],
"competitionType" : [
{
"_id" : [
ObjectId("60d8843f6ac43b6179d3bd7e"),
ObjectId("5ff457b2add6eab7491fff13"),
ObjectId("5fec0c53a534c297c6b4c5c3")
],
"competitionsTypeName" : [ "Programming Competition", "Presentation", "Animation/Documentary/Film" ]
}
]
},
/* 5 */
{
"_id" : [
ObjectId("60d8843f6ac43b6179d3bd7e")
],
"competitionType" : [
{
"_id" : [
ObjectId("60d8843f6ac43b6179d3bd7e")
],
"competitionsTypeName" : [ "Programming Competition" ]
}
]
}
相反,我需要得到这样的东西。
"competitionType" : [
{"_id" :ObjectId("5fec0c9fa534c297c6b4e4b6"),
"competitionsTypeName" : "AI/Robotics/IoT" },
{"_id" :ObjectId("5fec0c9fa534c297c6b4e4b6"),
"competitionsTypeName" : "AI/Robotics/IoT" },
{"_id" :ObjectId("5fec0c9fa534c297c6b4e4b6"),
"competitionsTypeName" : "AI/Robotics/IoT" }]
]
在浏览了一些mongodb的文章和论坛后,我迷路了,现在我不知道我错过了什么。
1条答案
按热度按时间zu0ti5jz1#
您将需要展开
studentAgeCategories
和competitionsType
使用
$group
删除重复项