0

我在 reddit 上抓取一些链接并将结果存储在 MongoDB 集合中。这是我的 Python 脚本中唯一存储数据的行:

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
                              )

我想将值推送到所有三个数组,但只'downs'存储在我的数据库中。我错过了什么?

我是 MongoDB 的新手,但是已经阅读过update并且push无法弄清楚我做错了什么。

4

2 回答 2

2

您需要将所有推送放在同一个元素中。以您编写的方式,不一定会推送最后一个-它可以是其中任何一个。

这是执行此操作的正确方法:

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
)

顺便说一句,$add 和其他修饰符也是如此。

于 2014-03-27T06:43:16.480 回答
0

因为 python 的键dict是不同的,对同一个键的多次赋值将导致只有最后一个赋值有效。

请看这个简短的例子:

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

但我认为您可以改用这种语法:

'$push': {'scores': (current_time, score),
          'ups': (current_time, ups),
          'downs': (current_time, downs)}
于 2014-03-27T06:37:47.537 回答