[英]Check if an element exist in mongodB
我想检查if语句中是否存在以dB为单位的数组。 到目前为止,我正在检查游标中的上述语句,但是我猜测它会减慢查询速度。 到目前为止,我的代码是:
编辑:行= [在open(input_file)中的行的line.rstrip()]
print len(lines)
row_no = len(lines)
col_no = len(lines)
matrix = sparse.lil_matrix((len(lines), len(lines)))
no_row = 0
counter = 0
for item in lines:
# find from database those items which their id exists in lines list and contain a follower_list
for cursor in collection.find({"_id.uid": int(item)}):
if cursor['list_followers'] is None:
continue
else:
id = cursor['_id']['uid']
counter+=1
print counter
print id
name = cursor['screenname']
# text.write('%s \n' %name)
followers = cursor['list_followers']
print len(followers)
for follower in followers:
try:
if (follower in lines) and (len(followers)>0):
matrix[no_row, lines.index(follower)] = 1
print no_row, " ", lines.index(follower), " ", matrix[no_row, lines.index(follower)]
except ValueError:
continue
no_row+=1
print no_row
scipy.io.mmwrite(output_file, matrix, field='integer')
最终,我发现延迟是由于创建了sparse.lil_matrix
我能想到的最接近的事情是实现稀疏索引并以不同的方式查询。 我将构造一个样本来演示:
{ "a" : 1 }
{ "a" : 1, "b" : [ ] }
{ "a" : 1 }
{ "a" : 1, "b" : [ ] }
{ "b" : [ 1, 2, 3 ] }
从本质上讲,您似乎要问的是只获取最后一个文档作为匹配,而不扫描所有内容。 这是一个不同的查询和一个稀疏索引的地方。 首先查询:
db.collection.find({ "b.0": { "$exists": 1 } })
仅返回1个项目,因为这是现有数组,在其第一个索引位置处有一些内容。 现在索引:
db.collection.ensureIndex({ "b": 1 },{ "sparse": true })
但是由于查询的性质,我们必须.hint()
这样:
db.collection.find({ "b.0": { "$exists": 1 } }).hint({ "b": 1 }).explain()
那将得到1个文档,而只考虑实际上具有数组的3个文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.