如何在 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" }
广告