检查元素是否存在于MongoDB中

0 投票
1 回答
3155 浏览
提问于 2025-04-18 12:45

我想在一个if语句中检查一个数组是否存在于数据库中。到目前为止,我是在游标中检查这个条件,但我觉得这样会让查询速度变慢。到现在为止我的代码是:

编辑: lines = [line.rstrip() for line in open(input_file)]

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。

1 个回答

1

我能想到的最接近的办法是实现一个稀疏索引,并稍微改变一下查询方式。我会构建一个示例来演示:

{ "a" : 1 }
{ "a" : 1, "b" : [ ] }
{ "a" : 1 }
{ "a" : 1, "b" : [ ] }
{ "b" : [ 1, 2, 3 ] }

基本上,你似乎是在问怎么只获取最后一个文档,而不需要扫描所有的文档。这时候,使用不同的查询方式和稀疏索引就能派上用场。首先是查询:

db.collection.find({ "b.0": { "$exists": 1 } })

这个查询只返回一个项目,因为这是现有数组中第一个位置有内容的项。接下来是索引:

db.collection.ensureIndex({ "b": 1 },{ "sparse": true })

但是由于查询的特性,我们需要用.hint()来提示一下:

db.collection.find({ "b.0": { "$exists": 1 } }).hint({ "b": 1 }).explain()

这样就能获取到那一个文档,并且只考虑到实际上有数组的三个文档。

撰写回答