我在MongoDB中拥有以下文档。
{
"_id" : ObjectId("5d5f9a3056be496aec564bca"),
"field1" : "value1",
"field2" : "value2",
}
如何查询并获得ObjectId
为String
。如下所示
{
"_id" : "5d5f9a3056be496aec564bca",
"field1" : "value1",
"field2" : "value2",
}
您可以使用$toString
运算符执行此任务。
db.collection.aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
field1: 1,
field2: 1
}
}
])
在MongoDB版本上> = 4.0
-您可以选择转换字段的类型,在这里您可以使用$toString将其转换为字符串:
db.collection.aggregate([
/** `$addFields` will overwrite the existing value of field if a field exists with same name,
* if not will create a new additional field on doc */
{
$addFields: {
_id: {
$toString: "$_id"
}
}
}
])
Test: mongoplayground
注意:在低于4.0
的版本上,除非使用任何代码来执行,否则无法使用MongoDB查询将ObjectId()
转换为字符串。