“更新” _id在mongodb文档中

发布于 2025-02-03 18:15:07 字数 548 浏览 2 评论 0原文

PS:我只需要这样做,因为业务需求,

我能够使用Mongosh来实现它,但是由于要更新有多个记录,我正在尝试实现一个简单的Python脚本来自动化任务。

可以使用pymongodb做到这一点吗?

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

我无法在DOC变量中设置新ID,以插入将镜像旧文档的新文档。

谢谢

PS: I only have to do this due to business requirements

I'm able to achieve it using mongosh, but since there are multiple records to be updated, I'm trying to implement a simple python script to automate the task.

Is it possible to do this with pymongodb?

// store the document in a variable
doc = db.clients.findOne({_id: ObjectId("4cc45467c55f4d2d2a000002")})

// set a new _id on the document
doc._id = ObjectId("4c8a331bda76c559ef000004")

// insert the document, using the new _id
db.clients.insert(doc)

// remove the document with the old _id
db.clients.remove({_id: ObjectId("4cc45467c55f4d2d2a000002")})

I'm not able to set the new Id in the doc variable in order to insert the new document that will mirror the old one.

Thanks

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

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

发布评论

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

评论(1

你爱我像她 2025-02-10 18:15:07

这是Pymongo等效的:

from pymongo import MongoClient
from bson import ObjectId

db = MongoClient()['mydatabase']

old_doc_id = '4cc45467c55f4d2d2a000002'
new_doc_id = '4c8a331bda76c559ef000004'

doc = db.clients.find_one({'_id': ObjectId(old_doc_id)})

if doc is not None:
    #  set a new _id on the document
    doc['_id'] = ObjectId(new_doc_id)

    # insert the document, using the new _id
    db.clients.insert_one(doc)

    # remove the document with the old _id
    db.clients.delete_one({'_id': ObjectId(old_doc_id)})

Here's a pymongo equivalent:

from pymongo import MongoClient
from bson import ObjectId

db = MongoClient()['mydatabase']

old_doc_id = '4cc45467c55f4d2d2a000002'
new_doc_id = '4c8a331bda76c559ef000004'

doc = db.clients.find_one({'_id': ObjectId(old_doc_id)})

if doc is not None:
    #  set a new _id on the document
    doc['_id'] = ObjectId(new_doc_id)

    # insert the document, using the new _id
    db.clients.insert_one(doc)

    # remove the document with the old _id
    db.clients.delete_one({'_id': ObjectId(old_doc_id)})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文