====== MongoDB for VS Code ======
===== Marketplace =====
[[https://marketplace.visualstudio.com/items?itemName=mongodb.mongodb-vscode|Install]]
* It is currently a preview version.
===== Usage =====
* 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.
{{ :development:tools:vscode:mongodb_for_vscode:screen_shot_2022-03-30_at_15.21.07.png?direct&400 |}}
Be careful when execute the playground file, especially when performing create and update actions.
===== Advance =====
* [[https://www.mongodb.com/docs/mongodb-vscode/|The MongoDB extension document]]
* Can require some npm packages into ''.mongodb'' file, [[https://www.mongodb.com/docs/mongodb-vscode/require-modules/|like taht]].
* [[https://www.mongodb.com/docs/mongodb-vscode/export-to-language/|Export a Query or Pipeline to Language]]
* Use javascript-like syntax.
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 }, // -or- { db: , coll: }
on: '_id',// -or- [ , ...] // Optional
// let: , // Optional
whenMatched: 'keepExisting', // // Optional
// whenNotMatched: // Optional
}
}
])
const afterInsert = db.getSiblingDB(TARGET_DB).getCollection(targetColl).countDocuments()
return {
from: `${SOURCE_DB}.${sourceColl}`,
to: `${TARGET_DB}.${targetColl}`,
beforeInsert,
insertCount,
afterInsert
}
})