mongodb - 在数组 mongodb 中查找重复项
问题描述
我有一个名为 Users 的 Mongo 集合,其结构如下
{
_id: '1234aaa',
profile: {
Organizations: [A,B,C,A,B,A]
}
},
{
_id: '1234bbb',
profile: {
Organizations: [A,B,C]
}
},
{
_id: '1234ccc',
profile: {
Organizations: [A,B,C,C]
}
}
仅当它们在 profile.organizations 下具有重复值时,如何返回我的集合中所有文档的列表。预期的结果是:
DupesUsers: {
{
User: '1234aaa,
Dupes: [A,B]
},
{
User: '1234ccc,
Dupes: [C]
},
}
我试过使用 Aggreagte:
db.getCollection('users').aggregate(
{$unwind: "$profile.organizations"},
{ $project: {_id: '$_id', org: '$profile.organizations'} },
{ $group: {
_id: null,
occurances: {$push: {'org': '$_id', count: '$count'}}
}
}
);
但我似乎无法理解它。
解决方案
只需进行一些细微的调整,您就离得不远了:
db.getCollection("users").aggregate(
[
{
"$unwind" : "$profile.organizations"
},
{
"$group" : {
"_id" : {
"dup" : "$profile.organizations",
"id" : "$_id"
},
"count" : {
"$sum" : 1.0
}
}
},
{
"$match" : {
"count" : {
"$gt" : 1.0
}
}
},
{
"$group" : {
_id: "$_id.id",
Dupes: {$push: "$_id.dup"}
}
}
],
);
推荐阅读
- angular - Angular 7 Observer 未定义
- php - 如何使用php一次在数据库中添加多条记录
- c# - 反射:从 List<> 的各个元素中获取属性/字段
- python - 在 Python 中使用列表推导进行素数分解
- c# - C# 客户端中的回声消除
- json - 当 JSON 不包含属性时,如何让 Json.NET 引发异常
- json - 如何从 couchbase 查询深层嵌套的 json 值?
- python - 如何在python中缓存类级别的属性?
- visual-studio-2015 - Skia C++ VS2015 项目设置
- angular - *ngIf 条件在 HTTP 请求完成后没有更新?