我有一个lessons
数组,其中包含supplementalLessonVideo
,这是一个对象。现在,我想使该字段成为名为supplementalLessonVideos
的数组,并通过查询将对象从supplementalLessonVideo
移动到第一个索引中。并非所有的课程都包含该字段,只有一些。
模式:
...
lessons: [
{
supplementalLessonVideo:
{
videoId: { type: Schema.Types.ObjectId, ref: "Video" },
_id: { type: Schema.Types.ObjectId },
fieldname: { type: String },
originalname: { type: String },
encoding: { type: String },
mimetype: { type: String },
filename: { type: String },
size: { type: Number },
key: { type: String },
url: { type: String },
},
},
];
并且我想加入:
...
lessons:[
{
supplementalLessonVideos:
[
{
videoId: { type: Schema.Types.ObjectId, ref: "Video" },
_id: { type: Schema.Types.ObjectId },
fieldname: { type: String },
originalname: { type: String },
encoding: { type: String },
mimetype: { type: String },
filename: { type: String },
size: { type: Number },
key: { type: String },
url: { type: String },
}
]
}
]
是否存在可以在数据库上编写并运行的查询,以将字段转换为数组,然后将对象数据移至数组的第一个索引?
因此,从这里开始:
"supplementalLessonVideo" : {
"videoId" : ObjectId("5ed868ab7c77482170d135f3"),
"_id" : ObjectId("5ed868ab7c77482170d135f4"),
"fieldname" : "supplemental-lesson-video",
"originalname" : "Student Navigation Video April 2018.mp4",
"encoding" : "7bit",
"mimetype" : "video/mp4",
"filename" : "supplemental-lesson-video-1591240848919-741719000",
"size" : 15255388,
"key" : "supplemental-lesson-video",
"url" : "https://vimeo.com"
},
对此:
"supplementalLessonVideos" : [{
"videoId" : ObjectId("5ed868ab7c77482170d135f3"),
"_id" : ObjectId("5ed868ab7c77482170d135f4"),
"fieldname" : "supplemental-lesson-video",
"originalname" : "Student Navigation Video April 2018.mp4",
"encoding" : "7bit",
"mimetype" : "video/mp4",
"filename" : "supplemental-lesson-video-1591240848919-741719000",
"size" : 15255388,
"key" : "supplemental-lesson-video",
"url" : "https://vimeo.com"
}],
答案 0 :(得分:1)
您可以使用。它创建一个数组并删除较旧的对象。
db.getCollection('test2').update({},[{
$set: {
supplementalLessonVideos: {
$concatArrays: [
[], //Creating new array
[{ //Adding values from object
videoId:"supplementalLessonVideo.videoId",
encoding:"supplementalLessonVideo.encoding"
}]
]
}}
},
{
$unset:"supplementalLessonVideo"
}])
updateMany
在这种情况下也适用。