我在MongoDB中有以下文档。
ct: Error: By default, won't create version with data identical to predecessor.
我该如何查询并以{
"_id" : ObjectId("5d5f9a3056be496aec564bca"),
"field1" : "value1",
"field2" : "value2",
}
的形式获得ObjectId
。像下面一样
String
答案 0 :(得分:1)
您可以使用$toString
运算符来完成此任务。
db.collection.aggregate([
{
$project: {
_id: {
$toString: "$_id",
},
field1: 1,
field2: 1
}
}
])
答案 1 :(得分:0)
在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"
}
}
}
])
测试: mongoplayground
注意:在4.0
以下的版本中,除非您使用任何代码来执行,否则无法使用MongoDB查询将ObjectId()
转换为字符串。