gpt4 book ai didi

python - mongodb pymongo从集合中消失的项目列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:21 26 4
gpt4 key购买 nike

因此,我通过从终端运行 $ mongod 来运行本地 mongodb。然后,我连接到它并使用 pymongo 使用 python 脚本创建一个小型数据库:

import random
import string
import pymongo

conn = pymongo.Connection("localhost", 27017)
collection = conn.db.random_strings

strings = numbers = []
for i in range(0,1000):
char_set = string.ascii_uppercase + string.digits
num_set = [ str(num) for num in [0,1,2,3,4,5,6,7,8,9] ]
strings.append( ''.join( random.sample( char_set * 6, 6 ) ) )
numbers.append( int(''.join( random.sample( num_set * 6, 6 ) ) ) )
collection.insert( { 'str' : strings[ i ], 'num' : numbers[ i ] } )

我现在有一个数据库,里面有很多随机字符串和数字。现在出现了令我烦恼且我不明白的事情:

things          = collection.find() 
first_list = list( things )
second_list = list( things )
print( first_list )
print( second_list )

第一个打印语句返回 1000 个对象的列表,而第二个打印语句返回一个空列表 ([])。为什么?

最佳答案

这一行:

things          = collection.find() 

实际上返回一个光标 (docs):

Returns an instance of Cursor corresponding to this query.

因此,当您从 things Cursor 创建 list 时,find 查询的整个结果返回并复制到 first_list 中。第二次,存储在 things 中的 Cursor 实例位于结果的末尾,因此,不再需要填充 second_list

关于python - mongodb pymongo从集合中消失的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18312840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com