我想更新一个文档的_id字段.我知道这不是很好的练习.但是由于一些技术原因,我需要更新它.

如果我try 更新它,我会得到:

db.clients.update({ _id: ObjectId("123")}, { $set: { _id: ObjectId("456")}})

Performing an update on the path '_id' would modify the immutable field '_id'

更新被拒绝.我如何更新它?

推荐答案

你不能更新它.您必须使用新的_id保存文档,然后删除旧文档.

// 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")})

Mongodb相关问答推荐

GO:如何在MongoDB中区分空字符串和nil

在对象mongodb的数组中查找元素

Mongo $sort然后$group,顺序能保证吗?

MongoDB 按日期时间字段查询 1h 间隔

根据条件删除一些数组元素并将数组的大小更新为mongo中的另一个文件

Pymongo API TypeError: Unhashable dict

Meteor mongo 驱动程序可以处理 $each 和 $position 运算符吗?

用 Redis 查询?

你如何让 mongo 在远程服务器上运行?

如何在 mongo JavaScript shell 中中止查询

$elemMatch 的 MongoDB 索引

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

Cannot connect to MongoDB errno:61

如何在 Meteor 应用程序之间共享 MongoDB 集合?

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

Mongodb错误:The positional operator did not find the match needed from the query

在 MongoDB 中为现有用户更改密码

无法将 Mongoose 连接到 Atlas

无法连接到远程服务器上的 mongo

在 mongoose 中使用 UUID 进行 ObjectID 引用