如何在 MongoDB 中更新 _id 字段?
你无法直接更新 _id 字段,即编写一些脚本来更新。我们首先创建一个包含以下文档的集合 −
> db.updatingIdFieldDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ce271bb36e8b255a5eee949")
}以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.updatingIdFieldDemo.find();
这将产生以下输出 −
{ "_id" : ObjectId("5ce271bb36e8b255a5eee949"), "StudentName" : "Chris" }以下是更新 MongoDB 中 _id 字段的查询 −
> var myDocument=db.updatingIdFieldDemo.findOne({StudentName:"Chris"});
> myDocument._id = 101;
101
> db.updatingIdFieldDemo.save(myDocument);
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 101 })
> db.updatingIdFieldDemo.remove({_id:ObjectId("5ce271bb36e8b255a5eee949")});
WriteResult({ "nRemoved" : 1 })让我们再次检查记录 −
> db.updatingIdFieldDemo.find();
这将产生以下输出。我们已成功更新 _id −
{ "_id" : 101, "StudentName" : "Chris" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP