MongoDB更新导致错误:位置运算符未从查询中找到所需的匹配项



我有一个MongoDb集合,里面有这样的对象

{
"_id": {
"$oid": "63016087246bdba9dec64a30"
},
"cards": [
{
"number": "1",
"have": "false"
},
{
"number": "2",
"have": "false"
},
{
"number": "3",
"have": "false"
},
{
"number": "4",
"have": "false"
},
],
"country": "Ecuador",
"sigla": "ECU"
}

我只想更新那些number: "1"

我正在运行这个代码:

const selectedCard = await Cards.findOne({ country: req.body.country, number: req.body.number })
if (selectedCard.cards[req.body.number - 1].have === 'false') {
await selectedCard.updateOne(
{
"cards.$.number": "1",
},
{
$set: {
"cards.$.have": "true"
}
}
)

但我一直收到The positional operator did not find the match needed from the query.错误,我不明白为什么。

find子句中不需要$

db.collection.update({
"cards.number": "1"
},
{
$set: {
"cards.$.have": "true"
}
})

这是Mongo游乐场供您参考。


此外,arrayFilters在操作数组字段时通常更具扩展性。

db.collection.update({},
{
$set: {
"cards.$[card].have": "true"
}
},
{
arrayFilters: [
{
"card.number": "1"
}
]
})

这是Mongo游乐场供您参考。

相关内容

  • 没有找到相关文章

最新更新