0
votes

I have a collection like the following:

{
    _id: ...,
    userId: test,
    cards: [
        { cardId: 166, qty: 2 },
        ...
    ]
}

I can send the following query to mongo to update a specific card:

db.getCollection('collections').update(
    { 'userId': 'test', 'cards.cardId': 166},
    { $set: {"cards.$.qty": 3} }
)

I also want to be able to create the card if it doesn't exist (ie. no card with such id) but the documentation says:

Do not use the positional operator $ with upsert operations because inserts will use the $ as a field name in the inserted document.

Is there any way around this? Can I do an update-if-exists/create with a single request to the database?

1

1 Answers

1
votes

try this way

db.getCollection('collections').update(
  { 'userId': 'test', 'cards.$.cardId': 166},
  { $set: {"cards.$.qty": 3} }
)

or

 db.getCollection('collections').update(
      { 'userId': 'test', 'cards.0.cardId': 166},
      { $set: {"cards.0.qty": 3} }
    )