简体   繁体   English

TypeError:列表索引必须是整数或切片,而不是ObjectId

[英]TypeError: list indices must be integers or slices, not ObjectId

I have a list of user user_list=["5c471d607f","5c63e9e46a","5c63e9e44e"] I am trying to insert it into mongodb to insert it inro mongodb my code is: 我有一个用户列表user_list=["5c471d607f","5c63e9e46a","5c63e9e44e"]我正在尝试将其插入mongodb中以将其插入mongodb中,我的代码是:

for i in range(0,len(user_list)):
    collection_4.update_one({'user_id':ObjectId(user_list[i])},{'$set':{'products': temp_list }},upsert=True)

This is giving me error, TypeError: list indices must be integers or slices, not ObjectId

While i am able to insert it when i tried: 虽然我可以在尝试时将其插入:

collection_4.update_one({'user_id':ObjectId("5c471d607f")},{'$set':{'products': temp_list }},upsert=True)

What is the problem with my code ? 我的代码有什么问题?

You must have another error in your script somewhere. 您的脚本中某处必须有另一个错误。 I can reproduce your error by doing the following: 我可以通过执行以下操作来重现您的错误:

from bson import ObjectId
l = ['a', 'b', 'c']
l[ObjectId('5c91ec870000000000000000')]

gives: 给出:

TypeError: list indices must be integers or slices, not ObjectId

Are you sure you're not attempting to slice a list anywhere using an ObjectId , rather than using an index? 您确定不是要使用ObjectId而不是使用索引对列表进行切片吗?

You might need to print more code because your current example seems to be ok. 您可能需要打印更多代码,因为您的当前示例似乎还可以。

One other improvement that @DirtyBit picked up, you can use enumerate to iterate over a list whilst tracking the index: @DirtyBit带来的另一项改进是,您可以使用enumerate遍历列表,同时跟踪索引:

for i, item in enumerate(user_list):
    collection_4.update_one({'user_id':ObjectId(item)},{'$set':{'products': temp_list }},upsert=True)

But then again, you don't require the index, so you could also just do: 但是再一次,您不需要索引,因此您也可以这样做:

for item in user_list:

try this 尝试这个

for i in range(0,len(user_list)):
    myid = user_list[i]
    collection_4.update_one({'user_id':str(myid)},{'$set':{'products': temp_list }},upsert=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM