MongoDB and Python: Multiple $push in same update. Only the last $push seems to be interpreted

StackOverflow https://stackoverflow.com/questions/22679827

  •  22-06-2023
  •  | 
  •  

Pregunta

I am crawling a some links on reddit and storing the results in a MongoDB collection. Here is the only line in my Python script that stores the data:

reddit_links_collection.update(
                               {'_id': id},                     # query
                               {                                # update rules
                                   '$set': {
                                             'title': title,
                                             'url': url
                                            },
                                   '$push': {'scores': (current_time, score)},
                                   '$push': {'ups': (current_time, ups)},
                                   '$push': {'downs': (current_time, downs)}

                               },
                               upsert=True                      # insert new if no one matches the query
                              )

I want to push values to all three arrays, but only 'downs' get stored in my database. What am I missing?

I am new to MongoDB, but have read about update and push and can't figure out what I am doing wrong.

¿Fue útil?

Solución

You need to put all pushes in the same element. In the way you wrote, not necessarily the last one will be pushed - it can be any of them.

Here is a correct way to do this:

reddit_links_collection.update(
   {'_id': id},
   {
      '$set': {
          'title': title,
          'url': url
       },
      '$push': {
          'scores': (current_time, score),
          'ups': (current_time, ups),
          'downs': (current_time, downs)
      },
      upsert=True
)

By the way, the same way is with $add, and other modificators.

Otros consejos

Because keys of a python dict are distinct, multiple assignment for the same key will result in only the last assignment being valid.

See this short example:

>>> {1: 2, 1: 3}
{1: 3}

But I think you can use this syntax instead:

'$push': {'scores': (current_time, score),
          'ups': (current_time, ups),
          'downs': (current_time, downs)}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top