为何 PyMongo 在记录中插入 _id 字段
2017-03-03 16:15
232 查看
如果待插入的文档没有 _id, MongoDB 会自动生成一个,但不会把结果返回个 PyMongo
对于需要写操作频繁的应用来说, 在写入之前复制一份插入 _id 代价可能会很高
如果你不想自动生成的 _id, 就需要自己在插入数据前 自己准备好 _id 字段
Why does PyMongo add an _id field to all of my documents?¶
When a document is inserted to MongoDB using insert_one(),
insert_many(),
or
bulk_write(),
and that document does not include an
_idfield, PyMongo automatically adds one for
you, set to an instance of
ObjectId.
For example:
>>> my_doc = {'x': 1} >>> collection.insert_one(my_doc) <pymongo.results.InsertOneResult object at 0x7f3fc25bd640> >>> my_doc {'x': 1, '_id': ObjectId('560db337fba522189f171720')}
Users often discover this behavior when calling
insert_many()with
a list of references to a single document raises
BulkWriteError.
Several Python idioms lead to this pitfall:
>>> doc = {} >>> collection.insert_many(doc for _ in range(10)) Traceback (most recent call last): ... pymongo.errors.BulkWriteError: batch op errors occurred >>> doc {'_id': ObjectId('560f171cfba52279f0b0da0c')} >>> docs = [{}] >>> collection.insert_many(docs * 10) Traceback (most recent call last): ... pymongo.errors.BulkWriteError: batch op errors occurred >>> docs [{'_id': ObjectId('560f1933fba52279f0b0da0e')}]
PyMongo adds an
_idfield in this
manner for a few reasons:
All MongoDB documents are required to have an
_idfield.
If PyMongo were to insert a document without an
_idMongoDB
would add one itself, but it would not report the value back to PyMongo.
Copying the document to insert before adding the
_idfield
would be prohibitively expensive for most high write volume applications.
If you don’t want PyMongo to add an
_idto
your documents, insert only documents that already have an
_idfield, added by your
application.
相关文章推荐
- oracle 分页显示,自增字段,返回插入记录ID
- MyBatis获取插入记录的自增长字段值(ID)
- 将刚插入的记录的自增Id,插入到另一个字段中
- MYSQL删除一个字段相同记录,保留ID最小记录
- ThinkPHP返回插入记录的id号
- Mybatis获取插入记录的自增长ID
- asp如何取得新插入记录的ID(ACCESS库和MSSQL方法不同) .
- SQL: 返回刚插入记录的ID 及 output 更新记录时得到更新记录的ID值 .
- 怎样在插入一条记录的同时,立即返回刚插入如记录的ID值
- SQL Server 返回最后插入记录的自动编号ID (Java语言)
- sqlite编程插入标示字段,获得新id
- java 插入表记录后得到自增的id (转) (附3种方法代码)
- 取得新插入记录id
- 关于含有标识字段的数据表中记录的插入问题解决(IDENTITY_INSERT)
- mysql查询ID相同的某字段最大那条记录
- spring Jdbctemplate返回插入记录的自增Id
- 插入记录后获取ID
- MyBatis返回插入记录的自增id
- 如何插入一条记录获取插入后的自动增长ID列的方法.
- C++Builder6中ADOQuery使用了lookup字段后如何插入记录