我有以下模式猫鼬,但有一个应用程序在生产与集合。这是对一个大得多的问题的简化,简化后便于理解。
这只是一个基本示例。
export const ListSchema = new Schema({
listaItemsIds: [
{
type: Schema.Types.ObjectId,
ref: 'Items',
default: [],
},
],
});
我需要将所有数据迁移到以下模型
export const ListSchema = new Schema({
listaItemsIds: [
{
item: {
type: Schema.Types.ObjectId,
ref: 'Items',
default: [],
},
property1: {
type: Number,
required: false,
default: 0,
},
property2: {
type: Number,
required: false,
default: 0,
},
},
],
});
下面的文档
{
"_id" : ObjectId("62bade11ff94fb9e5a0f5236"),
"listaItemsIds" : [
ObjectId("62a118a9167d269d38a4c806"),
ObjectId("62baef0cff94fb9e5a0f53e3"),
ObjectId("627bb4d61119d5ce2201b7df")
],
"__v" : 37
}
必须转换
{
"_id" : ObjectId("62bade11ff94fb9e5a0f5236"),
"listaItemsIds" : [
{
item:ObjectId("62a118a9167d269d38a4c806"),
property1:55,
property2:75,
},
{
item:ObjectId("62baef0cff94fb9e5a0f53e3"),
property1:55,
property2:75,
},
{
item:ObjectId("627bb4d61119d5ce2201b7df"),
property1:55,
property2:75,
},
],
"__v" : 37
}
我已经尝试了下面的代码片段,没有结果。
db.ListSchemas.updateMany({},
[
{$set: {"listaItemsIds.$[elem]":
{
item:"listaItemsIds.$[elem]",
property1:0,
property2:0,
}}}
]
);
肯定有更有经验的人能帮我。
可以这样写:
db.collection.update({},
[
{
$addFields: {
listaItemsIds: {
$map: {
input: "$listaItemsIds",
as: "id",
in: {
item: "$$id",
property1: 55,
property2: 75
}
}
}
}
}
],
{
multi: true
})
解释道:
使用$map替换数组以创建所需的对象。
游乐场