在单个记录中的MongoDB中的一系列对象中查找重复值
我是在 Mongo 中查询的新手。我有这条记录,我需要找到具有相同链接的部分。
我的记录:
{
"_id" : ObjectId("1234"),
"name": "singleRecordInMongo",
"__v" : 0,
"sections" : [
{
"name" : "firstElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1161")
},
{
"name" : "secondElement",
"link" : "https://www.test.com/",
"_id" : ObjectId("624dd0aca5fb565661da1162")
},
{
"name" : "thirdElement",
"link" : "https://www.other.com",
"_id" : ObjectId("624dd0aca5fb565661da1163")
}
]
}
预期结果:
"sections" : [
{
"times" : 2,
"link" : "https://www.test.com/"
}
]
我尝试了类似的方法,但没有成功
db.getCollection('records').aggregate(
{$unwind: "$sections"},
{ $project: {_id: '$_id', value: '$sections'} },
{ $group: {
_id: null,
occurances: {$push: {'value': '$link', count: '$count'}}
}
}
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:
您可以使用
$ group
:喜欢 playground> playground 返回:
Edit:
You can use
$group
:Like this playground returning:
用于使用JavaScript函数的综合操作, 操作员,您可以使用哈希地图来跟踪重复项,如下所示:
请记住
mongo playground
For an aggregate operation that uses JavaScript functions with the
$function
operator, you can use a hash map to keep track of duplicates as follows:Bear in mind
Mongo Playground