如何在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" }
这是将ObjectId转换为MongoDB聚合中的字符串值的查询。查询如下-
> db.objectidToStringDemo.aggregate([... {
... $project: {
... _id: {
... $toString: "$_id"
... }
... }
... }
... ]
... );
以下是输出-
{ "_id" : "5c92b80036de59bd9de0639d" }{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }
以上是 如何在MongoDB中将ObjectId转换为字符串 的全部内容, 来源链接: utcz.com/z/335338.html