您無法更新它,但可以保存新 ID 并刪除舊 ID。請按照一些步驟更新 MongoDB 的 _id。步驟如下:
第1步:第一步,需要將ObjectId存儲(chǔ)到變量中。
anyVariableName=db.yourCollectionName.findOne({_id:yourObjectIdValue)});
登錄后復(fù)制
第2步:在第二步中,您需要設(shè)置一個(gè)新的id。
yourDeclaredVariableName._id=yourNewObjectIdValue;
登錄后復(fù)制
第3步:在第三步中,您需要在文檔中插入新的ID。
db.yourCollectionName.insert(yourDeclaredVariableName);
登錄后復(fù)制
第4步:在第四步中,您需要?jiǎng)h除舊的ID。
db.yourCollectionName.remove({_id:yourOldObjectIdValue)});
登錄后復(fù)制
為了理解上述步驟,讓我們用文檔創(chuàng)建一個(gè)集合。使用文檔創(chuàng)建集合的查詢?nèi)缦拢?/p>
> db.updateIdDemo.insertOne({"StudentName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebfec6fd07954a4890683")
}
> db.updateIdDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebff66fd07954a4890684")
}
> db.updateIdDemo.insertOne({"StudentName":"Maxwell"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ebfff6fd07954a4890685")
}
登錄后復(fù)制
借助 find() 方法顯示集合中的所有文檔。查詢?nèi)缦拢?/p>
> db.updateIdDemo.find().pretty();
登錄后復(fù)制登錄后復(fù)制
以下是輸出:
{ "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" }
登錄后復(fù)制
以下是更新 MongoDB 文檔 _id 的查詢:
Step1:
> myId=db.updateIdDemo.findOne({_id:ObjectId("5c6ebfec6fd07954a4890683")});
{ "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" }
Step 2:
> myId._id=ObjectId("5c6ebfec6fd07954a4890689");
ObjectId("5c6ebfec6fd07954a4890689")
Step 3:
> db.updateIdDemo.insert(myId);
WriteResult({ "nInserted" : 1 })
Step 4:
> db.updateIdDemo.remove({_id:ObjectId("5c6ebfec6fd07954a4890683")});
WriteResult({ "nRemoved" : 1 })
登錄后復(fù)制
讓我們檢查 _id 是否已更新。借助 find() 方法顯示集合中的所有文檔:
> db.updateIdDemo.find().pretty();
登錄后復(fù)制登錄后復(fù)制
以下是輸出:
{ "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" }
{ "_id" : ObjectId("5c6ebfec6fd07954a4890689"), "StudentName" : "Robert" }
登錄后復(fù)制
查看示例輸出,“StudentName”:“Robert” 的 _id 已更改。
以上就是如何更新 MongoDB 文檔的 _id?的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!






