I have a MongoDb collection with objects like this
{
"_id": {
"$oid": "63016087246bdba9dec64a30"
},
"cards": [
{
"number": "1",
"have": "false"
},
{
"number": "2",
"have": "false"
},
{
"number": "3",
"have": "false"
},
{
"number": "4",
"have": "false"
},
],
"country": "Ecuador",
"sigla": "ECU"
}
And I want to update only those where number: "1"
I'm running this code:
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"
}
}
)
but I keep getting the The positional operator did not find the match needed from the query.
error and I can't understand why.
CodePudding user response:
You don't need the $
in the find
clause.
db.collection.update({
"cards.number": "1"
},
{
$set: {
"cards.$.have": "true"
}
})
Here is the Mongo playground for your reference.
In addition, arrayFilters
is generally more extensible for manipulating array fields.
db.collection.update({},
{
$set: {
"cards.$[card].have": "true"
}
},
{
arrayFilters: [
{
"card.number": "1"
}
]
})
Here is the Mongo playground for your reference.