如何在 MongoDB 中將 ObjectId 轉換成字串
為了將 ObjectId 轉換成字串,請在 MongoDB 中使用 $toString。為了理解以上概念,讓我們建立一個包含文件的集合。建立文件集合的查詢如下 −
> db.objectidToStringDemo.insertOne({"UserName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b80036de59bd9de0639d")
}
> db.objectidToStringDemo.insertOne({"UserName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b80436de59bd9de0639e")
}
> db.objectidToStringDemo.insertOne({"UserName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b80936de59bd9de0639f")
}
> db.objectidToStringDemo.insertOne({"UserName":"Robert"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b81836de59bd9de063a0")
}使用 find() 方法從集合中顯示所有文件。查詢如下 −
> db.objectidToStringDemo.find().pretty();
以下是輸出 −
{ "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" }以下是在 MongoDB 聚合中將 ObjectId 轉換成字串值的查詢。查詢如下 −
> db.objectidToStringDemo.aggregate([
... {
... $project: {
... _id: {
... $toString: "$_id"
... }
... }
... }
... ]
... );以下是輸出 −
{ "_id" : "5c92b80036de59bd9de0639d" }
{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP