比方说,我有一份投资者名单,每一个人,我们都会记录他们持有哪些公司的股票,以及他们持有多少:
"investors": [
{
"userID": 0,
"investments": [
{
"company": "Google",
"shares": 3
},
{
"company": "Amazon",
"shares": 5
}
]
}
]所以在这个例子中,ID为0的人在Google中有3股,在Amazon中有5股。我试图写一个猫鼬请求,我可以用它来增加投资者的新股,不管它是否是一家新公司。到目前为止,我的最佳尝试是:
Investor.updateOne(
{ 0 },
// newInvestments is an array that contains all new investments that should be added to the database
{ userID: 0, $set: { investments: newInvestments } },
{ upsert: true }
)在添加新公司时,这很好,但是对于用户已经拥有股份的公司,旧的价值将被新的公司覆盖。举个例子,如果这个人多买2股谷歌股票,我们会希望他们的股票涨到5股,但这样的话,它就会被2股所取代。
我相信我想要实现的目标可以使用$inc来完成,但是我无法在这个特定的场景中找到语法。我是MongoDB的新手--欢迎你提出任何建议。
发布于 2022-01-31 17:04:47
使用javascript很简单:
push新的投资或增量shares (如果存在的话)doc.save()const investor = await Investor.findById(0);
newInvestments.forEach(newInv => {
const index = investor.investments.findIndex(inv => inv.company === newInv.company);
if(index === -1) {
investor.investments.push(newInv);
} else {
investor.investments[index].shares += newInv.shares;
}
});
investor.save()https://stackoverflow.com/questions/70928248
复制相似问题