-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremoveDuplicates.js
More file actions
49 lines (43 loc) · 1.38 KB
/
removeDuplicates.js
File metadata and controls
49 lines (43 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// removeDuplicates.js
const mongoose = require('mongoose');
require('dotenv').config(); // Load environment variables
// MongoDB Atlas connection URI
const uri = process.env.MONGODB_URI; // Store your connection string in .env
// Connect to MongoDB
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Connected to MongoDB!");
removeDuplicates();
}).catch(err => {
console.error("Error connecting to MongoDB:", err);
});
const Song = require('./models/song'); // Adjust the path to your Song model
async function removeDuplicates() {
try {
const duplicates = await Song.aggregate([
{
$group: {
_id: { url: "$url" },
uniqueIds: { $addToSet: "$_id" },
count: { $sum: 1 }
}
},
{
$match: {
count: { $gt: 1 }
}
}
]);
for (const duplicate of duplicates) {
const [firstId, ...duplicateIds] = duplicate.uniqueIds;
await Song.deleteMany({ _id: { $in: duplicateIds } });
}
console.log('Duplicates removed successfully');
mongoose.connection.close();
} catch (error) {
console.error('Error removing duplicates:', error);
mongoose.connection.close();
}
}