在 MongoDB 中查找重复名称

Find duplicate name in MongoDB

我在 mongodb 中获取重复名称以删除重复项时遇到问题。

{
    "users": [
      {
        "_id": {
          "$oid": "61441890a6566a001623b8ed"
        },
        "name": "Jollibee",
      },
      {
        "_id": {
          "$oid": "61441890a6566a001623b8ed"
        },
        "name": "Jollibee",
      },
      {
        "_id": {
          "$oid": "61441890a6566a001623b8ed"
        },
        "name": "MCDO",
      },
      {
        "_id": {
          "$oid": "61441890a6566a001623b8ed"
        },
        "name": "Burger King",
      },
    ]
  }

我只想在输出中显示重复的名称。这是 Jollibee.

尝试过这种方法,但它只 returns 我计算了所有用户的数量,而不是重复的用户。我只想显示 2 Jollibee

db.collection.aggregate([
  {
    "$unwind": "$users"
  },
  {
    "$group": {
      "_id": "$_id",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$match": {
      "_id": {
        "$ne": null
      },
      "count": {
        "$gt": 1
      }
    }
  }
])

因为 $unwind 步骤为所有文档提供相同的 _id_id 分组是不正确的。而是尝试按 users.name

分组
db.collection.aggregate([
  {
    "$unwind": "$users"
  },
  {
    "$group": {
      "_id": "$users.name",
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$match": {
      "_id": {
        "$ne": null
      },
      "count": {
        "$gt": 1
      }
    }
  }
])

demo

假设文档是:

[
    {
        "_id": {
            "$oid": "6226dd742ef592186422ad1d"
        },
        "name": "Stack test"
    },
    {
        "_id": {
            "$oid": "6226dd7d2ef592186422ad1e"
        },
        "name": "Stack test"
    },
    {
        "_id": {
            "$oid": "6226dd912ef592186422ad1f"
        },
        "name": "Stack test 001"
    }
]

聚合查询:

db.users.aggregate(
    [
        {
            $group: {
                _id: "$name", 
                names: {$push: "$name"}
            }
        }
    ]
)

结果:

{ 
    _id: 'Stack test', 
    names: [ 'Stack test', 'Stack test' ] 
},
{ 
    _id: 'Stack test 001', 
    names: [ 'Stack test 001' ] 
}

但更好的方法是

聚合查询:

db.users.aggregate(
    [
        {
            $group: {
                _id: "$name", 
                count: {$sum: 1}
            }
        }
    ]
)

结果:

{ 
    _id: 'Stack test',
    count: 2 
},
{ 
    _id: 'Stack test 001', 
    count: 1 
}

现在,您可以遍历计数并使用 _id

中的名称值