development:tools:vscode:mongodb_for_vscode:start

MongoDB for VS Code

Install

  • It is currently a preview version.
  • Open vscode preference and search 'MongoDB'.
  • Please keep Ask before executing command selected.
  • Please keep connection saving globally.
  • Add some .mongodb playground file into ${workspaceFolder}/.vscode/mongo/.
  • Delete the exclude folder '**/.*'.
  • You will see your playground files.

Be careful when execute the playground file, especially when performing create and update actions.
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
  }
})
  • development/tools/vscode/mongodb_for_vscode/start.txt
  • Last modified: 2022/04/07 17:12
  • by joe.mao