我在 MongoDB 中有一个集合,其中一个文档如下所示:
{
_id: ObjectId("6162883719592ea3350d3c87"),
fullName: 'Random User',
username: 'ruser1',
password: 'asdadasd',
portfolio: [ { equity: [] }, { crypto: [] }, { etf: [] }, { cash: [] } ]
}
我正在尝试将以下格式的新对象附加到equity投资组合内的数组中。
对象格式:
{
name : "AAPL",
quantity : 1,
price : 100
}
我试图使用$push来执行此操作,但遇到以下错误:
db.users.updateOne(
{_id : ObjectId("6162883719592ea3350d3c87")},
{$push : {"portfolio.equity" : {
name : "AAPL",
quantity : 1,
price : 100
}
}
}
)
MongoServerError: Cannot create field 'equity' in element {portfolio: [ { equity: [] }, { crypto: [] }, { etf: [] }, { cash: [] } ]}
我也尝试过使用portfolio.$.equity,但这也不起作用。
db.users.updateOne(
{_id : ObjectId("6162883719592ea3350d3c87")} ,
{$push : {"portfolio.$.equity" : {name : "AAPL", price : 100, quantity : 1}}}
)
MongoServerError: The positional operator did not find the match needed from the query.
简而言之,我试图将一个对象附加到对象对象内的数组中。
我该如何解决此错误或执行此操作的适当方法是什么?