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

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

问题描述

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

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

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

在插入注释文档后,我需要立即获取对象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.

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

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的一件很酷的事情就是ID是在客户端生成的.

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
4f0b2f55096f7622f6000000

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

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