const SOURCE_DB = 'timesheetapp'
const TARGET_DB = 'ecoffice'
const COLLECTION_SET = [
{ sourceColl: 'customers', targetColl: 'customers' },
{ sourceColl: 'timesheetJobs', targetColl: 'timesheetJobs' },
{ sourceColl: 'timesheetServices', targetColl: 'timesheetServices' }
]
// Select the database to use.
use(SOURCE_DB)
COLLECTION_SET.map((obj) => {
const { sourceColl, targetColl } = obj
const beforeInsert = db.getSiblingDB(TARGET_DB).getCollection(targetColl).countDocuments()
const insertCount = db[sourceColl].countDocuments({
companyCode: '681584241825192'
})
const result = db[sourceColl].aggregate([
{
$match: {
companyCode: '681584241825192'
}
},
// if you need to add fields
{
$addFields: {
tenantCode: "$companyCode" // use reference
}
},
// Mongo project
{
$project: {
companyCode: 0
}
},
// reference https://docs.mongodb.com/manual/reference/operator/aggregation/merge/#only-insert-new-data
// Starting in MongoDB 4.4
{
$merge: {
into: { db: TARGET_DB, coll: targetColl }, // <collection> -or- { db: <db>, coll: <collection> }
on: '_id',// <identifier field> -or- [ <identifier field1>, ...] // Optional
// let: <variables>, // Optional
whenMatched: 'keepExisting', // <replace|keepExisting|merge(Default)|fail|pipeline> // Optional
// whenNotMatched: <insert(Default)|discard|fail> // Optional
}
}
])
const afterInsert = db.getSiblingDB(TARGET_DB).getCollection(targetColl).countDocuments()
return {
from: `${SOURCE_DB}.${sourceColl}`,
to: `${TARGET_DB}.${targetColl}`,
beforeInsert,
insertCount,
afterInsert
}
})