X
X
Xokare2282020-07-23 15:13:19
MongoDB
Xokare228, 2020-07-23 15:13:19

How to update an object in an array?

there is an object

{
    "_id": {
        "$oid": "5f197d2a61d795fc53af6f0e"
    },
    "article_id": 1,
    "views": [{'23072020-11': 1}],
    "dislikes": [],
    "likes": []
}


Need to increase the value in {'23072020-11': 1} by 1
Tried different queries, the last one stopped at
analytics.update_one({'article_id': a_id, type: [t]}, {'$inc': {f'{type}.$': {t: 1}}})

But it doesn't work
In t variable - 23072020-11, in type - 'views'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-07-24
@Xokare228

"views": [{'23072020-11': 1}]
this is terrible, it's already a finished project with a full database, where you can't change it to something like ... ?

"views": [
  { 
    date: '23072020-11',   // а еще лучше в формате Date, а не строкой
    count: 1
  }
]

analytics.update_one(
  { article_id: a_id, 'views.date': '23072020-11' }, // тогда было бы несложно получить объект
  { $inc: {
       'views.$.count': 1  // и как-то так получилось бы
    }
  }
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question