Computer >> Máy Tính >  >> Lập trình >> MongoDB

Tìm bản ghi trùng lặp trong MongoDB?


Bạn có thể sử dụng khung tổng hợp để tìm các bản ghi trùng lặp trong MongoDB. Để hiểu khái niệm, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -

> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a330293b406bd3df60e01")
}
> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a330493b406bd3df60e02")
}
> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a330c93b406bd3df60e03")
}
> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a331093b406bd3df60e04")
}
> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a331593b406bd3df60e05")
}
> db.findDuplicateRecordsDemo.insertOne({"StudentFirstName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a331e93b406bd3df60e06")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

> db.findDuplicateRecordsDemo.find();

Sau đây là kết quả -

{ "_id" : ObjectId("5c8a330293b406bd3df60e01"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5c8a330493b406bd3df60e02"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5c8a330c93b406bd3df60e03"), "StudentFirstName" : "Carol" }
{ "_id" : ObjectId("5c8a331093b406bd3df60e04"), "StudentFirstName" : "Sam" }
{ "_id" : ObjectId("5c8a331593b406bd3df60e05"), "StudentFirstName" : "Carol" }
{ "_id" : ObjectId("5c8a331e93b406bd3df60e06"), "StudentFirstName" : "Mike" }

Đây là truy vấn để tìm các bản ghi trùng lặp trong MongoDB -

> db.findDuplicateRecordsDemo.aggregate(
   ... {"$group" : { "_id": "$StudentFirstName", "count": { "$sum": 1 } } },
   ... {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
   ... {"$project": {"StudentFirstName" : "$_id", "_id" : 0} }
... );

Sau đây là đầu ra chỉ hiển thị các bản ghi trùng lặp -

{ "StudentFirstName" : "Carol" }
{ "StudentFirstName" : "John" }