mongodb在聚合时从同一文档的数组中获取唯一值



我正在查询从嵌套数组文档中检索唯一的对象数组,因此我在其中使用aggregation和$group。

My Data Structure

{
_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的一些文章和论坛后,我迷路了,现在我不知道我在这里错过了什么。

您需要展开studentAgeCategoriescompetitionsType

db.clnEvents.aggregate([
{
$match: {
_id: ObjectId("62c3e2c03c004872845b2766")
}
}, 
{
$unwind: '$studentAgeCategories'
}, 
{
$unwind: '$studentAgeCategories.competitionsType'
}, 

{
$project: {
competitionsTypeId: '$studentAgeCategories.competitionsType.competitionsTypeId',
competitionsTypeName: '$studentAgeCategories.competitionsType.competitionsTypeName'
}
},
{
$group: {
_id: '$competitionsTypeId',
competitionsTypeName: {
$first: '$competitionsTypeName'
}
}
}

])

使用$group删除重复项

最新更新