我在MongoDB中的每个文档中都保存了一个名为“ track”的字段。每个对象内部都有一个对象,其对象带有诸如“ 0”,“ 1”等的键。我必须用数组替换这部分。
实际情况
"track" : {
"0" : {
"name" : "Crossdromo A",
"type" : "Motocross"
},
"1" : {
"name" : "Crossdromo B",
"type" : "Minicross"
}
}
Desiderata
"track" : [
{
"name" : "Crossdromo A",
"type" : "Motocross"
},
{
"name" : "Crossdromo B",
"type" : "Minicross"
}
]
关于如何更改此设置的任何建议?
答案 0 :(得分:0)
您可以使用以下aggregation:
db.getCollection('samples').aggregate([{ //Replace 'samples' with your collection name
$match: {} //You can change this to any query if you don't want to apply it to all documents in the collection
},
{
$addFields: {
track: {
$objectToArray: '$track' //This converts it to [{k: '0', v: { "name" : "Crossdromo A", "type" : "Motocross" }}, {k: 1,..]
}
}
}, {
$addFields: {
track: '$track.v' //This pulls the 'v' key from the previous object.
}
}, {
$out: 'samples' //Replace 'samples' with your collection name
}])