如何使用 pymongo 将 select 个文档从一个集合复制到另一个集合?
How to copy select documents from one collection to another with pymongo?
我一直在将 Twitter 上的数据传输到 mongo 数据库中。但是我发现我没有错误地格式化搜索,所以我从各地而不是我想要的一个城市获取数据(我通过检查城市名称是否出现在 'location' 或 [= json 中 'user' 下的 32=]。
我只想将正确的文档复制到新集合中,但我发现在 pymongo 中几乎不可能做到!我使用 pymongo 而不是 shell 因为我使用正则表达式来搜索城市名称(它有很多同义词)。
regex=re.compile(<\really long regular expression of city names>)
我已经能够通过正则表达式正确使用 find();它 returns 正是我要找的:
db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in':[regex]}}]})
我只需要将它 returns 的内容复制到一个新的集合中,但事实证明这很困难。
我试了this method, trying forEach() to try to copy the documents, using bson wrapping, which I found here,还是不行。
db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in' [regex]}}]})\
.forEach(bson.Code( '''
function(doc) {
db.subset.insert(doc);
}'''))
具体来说,我尝试此操作时遇到的错误是
AttributeError: 'Cursor' 对象没有属性 'forEach'
我不知道出了什么问题,也不知道该如何解决。谁能告诉我如何解决这个问题,或者有更好的方法将文档复制到新集合?
游标已经能够遍历您不需要 forEeach 的结果。尝试
for tweet in db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in' [regex]}}]}):
db.subset.insert(tweet)
我一直在将 Twitter 上的数据传输到 mongo 数据库中。但是我发现我没有错误地格式化搜索,所以我从各地而不是我想要的一个城市获取数据(我通过检查城市名称是否出现在 'location' 或 [= json 中 'user' 下的 32=]。
我只想将正确的文档复制到新集合中,但我发现在 pymongo 中几乎不可能做到!我使用 pymongo 而不是 shell 因为我使用正则表达式来搜索城市名称(它有很多同义词)。
regex=re.compile(<\really long regular expression of city names>)
我已经能够通过正则表达式正确使用 find();它 returns 正是我要找的:
db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in':[regex]}}]})
我只需要将它 returns 的内容复制到一个新的集合中,但事实证明这很困难。
我试了this method, trying forEach() to try to copy the documents, using bson wrapping, which I found here,还是不行。
db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in' [regex]}}]})\
.forEach(bson.Code( '''
function(doc) {
db.subset.insert(doc);
}'''))
具体来说,我尝试此操作时遇到的错误是
AttributeError: 'Cursor' 对象没有属性 'forEach'
我不知道出了什么问题,也不知道该如何解决。谁能告诉我如何解决这个问题,或者有更好的方法将文档复制到新集合?
游标已经能够遍历您不需要 forEeach 的结果。尝试
for tweet in db.coll.find({'$or':[{'user.location':{'$in':[regex]}},{'user.name':{'in' [regex]}}]}):
db.subset.insert(tweet)