Pymongo forEach格式 [英] Pymongo forEach formatting

查看:86
本文介绍了Pymongo forEach格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何格式化forEach函数,使其可以搁在多行上而不会引起语法错误?

How can I format a forEach function so that it can rest on multiple lines without causing a syntax error? Something like

self.request.db.myCollection.find().forEach( 
    function(u) { 
       u.forSong = self.request.db.song.find_one({}, {'_id': 1})
       self.request.db.save(u)
     })

推荐答案

要从Python传入JavaScript代码,您需要将其包装在

To pass javascript code in from Python, you need to wrap it in a bson.Code object, since otherwise Python itself (rather than PyMongo) will try to parse it. This gives you:

import bson
self.request.db.myCollection.find().forEach(bson.Code( '''
    function(u) { 
       u.forSong = self.request.db.song.find_one({}, {'_id': 1})
       self.request.db.save(u)
     }'''))

但是您在其中使用self的事实使您看起来好像要在其中使用Python代码,而不是javascript代码.从文档来看,从find返回的Cursor对象实现了Python的Sequence协议-意味着您应该只能使用常规的Python循环而不是forEach(文档似乎说PyMongo仍然不实现):

But the fact that you're using self in there makes it look like you want to use Python code there, not javascript code. From the documentation, it looks like the Cursor object returned from find implements Python's Sequence protocol - meaning you ought to just be able to use a regular Python loop instead of forEach (which the docs seem to say that PyMongo doesn't implement anyway):

for u in self.request.db.myCollection.find():
   u.forSong = self.request.db.song.find_one({}, {'_id': 1})
   self.request.db.myCollection.save(u)

这篇关于Pymongo forEach格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆