MongoDB#常用脚本

批量插入数据脚本

const oneDayAgo  = new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);

const documents = [];
for (let i = 1; i <= 100; i++) {
  documents.push({
	id: i, // 递增的 id
	createTime: oneDayAgo, // 1天前的日期
	data: `Sample data ${i}` // 其他字段(可选)
  });
}
// 创建test_data collection
db.test_data.inserMany(documents);

多collection关联删除脚本

const batchSize = 10000;
let deletedCount = 0;

do {
  // 1. 查询集合 B 中符合条件的 xxxId
  const xxxIdsToDelete = db.B.find(
    { status: { $ne: 1 } },
    { xxxId: 1, _id: 0 }
  ).toArray().map(doc => doc.xxxId);

  // 2. 删除集合 A 中符合条件的文档
  const result = db.A.deleteMany(
    {
      xxxId: { $in: xxxIdsToDelete }
    },
    { limit: batchSize } // 每批最多删除 batchSize 条数据
  );

  deletedCount = result.deletedCount;
  print(`已删除 ${deletedCount} 条数据`);
} while (deletedCount > 0);

你可能感兴趣的:(#,MongoDB,mongodb,数据库)