[英]Mongo shell script - How to use libraries?
在 Mongo shell 脚本中,我需要读取文件以按 _id 删除文档,但我无法导入 FileReader 库。
我从 bash 启动脚本来执行简单的 find() 并且它可以工作:
mongosh --host xxx --port 27017 --username xxx --password xxx --eval "var country='$country';var file='$inputDataFile'" --file scriptFile.js
但是每当我尝试在 js 中导入库时,它都会显示错误:
TypeError: Cannot assign to read only property 'message' of object 'SyntaxError:
'import' and 'export' may appear only with 'sourceType
我从 nodejs 调用的同一个 js 文件并且导入是正确的。
现在我使用nodejs删除文件中包含的_ids。 我想为我的所有查询找到一种使用 Mongo shell 脚本的方法
我设法在脚本中包含外部文件和模块的帮助下解决了我的问题
1- Create package.json in the same directory as your js 2- Add the necessary libraries to package.json 3- Install libraries 4- Use require to import it
代码
var fs = require('fs');
console.log(country)
console.log(file)
db = db.getSiblingDB('mongotest')
const allFileContents = fs.readFileSync(file, 'utf-8');
var lines = allFileContents.split("\r")
for (var i = 0; i < lines.length; i++) {
const user = JSON.parse(lines[i]);
var userId = user._id
if (!(userId instanceof ObjectId)) {
userId = new ObjectId(userId);
}
db.userChat.deleteOne({ _id: userId })
}
谢谢你的帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.