我正在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
,无法找出我做错了什么
你需要把所有的push放到同一个元素中。按照你写的方式,不一定是最后一个——可以是其中任何一个。
正确的做法是:
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和其他修饰符也是如此。
由于python dict
的键是不同的,因此对同一键的多次赋值将导致只有最后一次赋值有效。
请看这个简短的例子:
>>> {1: 2, 1: 3}
{1: 3}
但是我认为你可以用这个语法来代替:
'$push': {'scores': (current_time, score),
'ups': (current_time, ups),
'downs': (current_time, downs)}