让我们看一个示例,以了解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()
method的帮助下显示集合中的所有文档。查询如下-
> 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" }
为了获得原始的ObjectId,请使用$toObjectId运算符-
> db.objectidToStringDemo.aggregate([ { $project: { _id: { $toObjectId: "$_id" } } } ] );
以下是输出-
{ "_id" : ObjectId("5c92b80036de59bd9de0639d") } { "_id" : ObjectId("5c92b80436de59bd9de0639e") } { "_id" : ObjectId("5c92b80936de59bd9de0639f") } { "_id" : ObjectId("5c92b81836de59bd9de063a0") }