mongodb - 如何在 MongDB:s 函数中使用 Insert
问题描述
目标:使用 MongoDB 的函数通过使用函数添加新行。
在 SQL Server 中使用存储过程添加新行的概念类似。
问题:代码不起作用,我缺少什么部分?
{
"message" : "db.Test.myAddFunction is not a function",
"stack" : "script:1:10"
}
信息:我是 MongoDB 新手
db.createCollection("Test")
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
db.system.js.save(
{
_id : "myAddFunction" ,
value : function (x, y)
{
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
return x + y;
}
}
);
db.loadServerScripts();
db.Test.myAddFunction(2, 2);
解决方案
你不能。
在 system.js 集合中保存函数后,您可以在任何 JavaScript 上下文中使用该函数;例如$where运算符、mapReduce命令或db.collection.mapReduce()。
来源:https ://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/