嗨,我该如何在pymongo中使用foreach()

发布于 2025-02-05 07:26:19 字数 290 浏览 3 评论 0原文

我有一些集合。我想用汇总代码搜索一些条件和数据。然后在pymongo中使用foreach代码更新结果。是否可以? 例如,我写一个代码:

db.users.find({age: {$gt: 18}}).forEach( function(myDoc) {db.users.updateOne({_id: myDoc._id }, {$set: {type: "older"}} ); 

我想写这篇文章是在Pymongo中。

I have some collection. I want to search with some condition and data with aggregate code. Then update result with forEach code in pymongo. Is it possible?
For example i write a code:

db.users.find({age: {$gt: 18}}).forEach( function(myDoc) {db.users.updateOne({_id: myDoc._id }, {$set: {type: "older"}} ); 

I want to write this is in pymongo.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏雨一样淡蓝的深情 2025-02-12 07:26:19

查看您的代码,如果要在与某个条件匹配的所有记录上设置字段#pymongo.collection.collection.update_many“ rel =“ nofollow noreferrer”> update_many() 而无需使用for for循环。

from pymongo import MongoClient
db = MongoClient()['mydatabase']
db.users.update_many({'age': {'$gt': 18}}, {'$set': {'type': 'older'}})

Looking at your code, if you want to set a field on all records matching a certain criteria, you can just use update_many() without the need for a for loop.

from pymongo import MongoClient
db = MongoClient()['mydatabase']
db.users.update_many({'age': {'$gt': 18}}, {'$set': {'type': 'older'}})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文