如何更新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" }热门推荐
10 商务感恩祝福语大全简短
11 同事生日祝福语简短独特
12 朋友出国读书祝福语简短
13 春节新年祝福语简短幽默
14 简短的祝福语中秋搞笑
15 牛年公司新年祝福语简短
16 幽默的新娘祝福语简短
17 祝女儿六一祝福语简短
18 祝福语闺蜜简短单纯