插入后如何在 PyMongo 中获取对象 ID? [英] How to get the object id in PyMongo after an insert?

查看:31
本文介绍了插入后如何在 PyMongo 中获取对象 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对 Mongo 进行简单的插入...

I'm doing a simple insert into Mongo...

db.notes.insert({ title: "title", details: "note details"})

note文档插入后,需要立即获取object id.从插入返回的结果包含一些关于连接和错误的基本信息,但没有文档和字段信息.

After the note document is inserted, I need to get the object id immediately. The result that comes back from the insert has some basic info regarding connection and errors, but no document and field info.

我发现了一些关于使用 upsert=true 的 update() 函数的信息,我只是不确定这是否是正确的方法,我还没有尝试过.

I found some info about using the update() function with upsert=true, I'm just not sure if that's the right way to go, I have not yet tried it.

推荐答案

MongoDB 的一个很酷的地方是 ids 是在客户端生成的.

One of the cool things about MongoDB is that the ids are generated client side.

这意味着您甚至不必询问服务器 id 是什么,因为您一开始就告诉它要保存什么.使用 pymongo,插入的返回值将是对象 id.看看吧:

This means you don't even have to ask the server what the id was, because you told it what to save in the first place. Using pymongo the return value of an insert will be the object id. Check it out:

>>> import pymongo
>>> collection = pymongo.Connection()['test']['tyler']
>>> _id = collection.insert({"name": "tyler"})
>>> print _id.inserted_id 
4f0b2f55096f7622f6000000

这篇关于插入后如何在 PyMongo 中获取对象 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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