[英]How to pass value from an attribute to another attribute of the same collection?
[英]How to add attribute to all documents in a collection, with same data of another attribute in MongoDB?
我见过这个问题,它可能很有用,但我需要一些额外的步骤。
我有一个Sites
集合,其中填充了name
、 data
和一个名为infoBox
的字段,它是一个对象。
infoBox: {
coordX: {
type: Number,
},
coordY: {
type: Number,
},
type: {
type: Number,
enum: [InfoBoxType.line, InfoBoxType.horizontal, InfoBoxType.vertical],
},
midPoint: {
coordX: {
type: Number,
},
coordY: {
type: Number,
},
},
因此,我需要向名为“ levels
”的站点的所有信息框添加另一个属性,该属性是一个数组,并且该字段必须包含两个对象,例如InfoBox
,具有相同的值,但“级别”为空。 (信息框 1 和 2 具有相同的值)。这是初始化数据库,稍后这些值将由用户编辑。
为了清楚起见,我实际上有:
Site
data
name
infobox
coordx
coordy
midpoint
coordx
coordy
我需要
Site
data
name
infobox
coordx
coordy
midpoint
coordx
coordy
levels
infobox1
coordx
coordy
midpoint
coordx
coordy
levels(empty)
infobox2
coordx
coordy
midpoint
coordx
coordy
levels(empty)
我怎样才能做到这一点?
额外信息:Mongo 4.2 版
编辑
我正在尝试使用这样的方法来实现它,但还没有运气:
let sites = await this.siteModel.find({});
const firstZoom = site.infoBox;
const secondZoom = site.infoBox;
const levelss = [
firstZoom,
secondZoom,
];
await this.siteModel.update({ _id: site._id }, { $set: { 'infoBox.levels.$': levelss } });
在支持更新操作中的聚合管道的 MongoDB v 4.2
上,您可以尝试这个(您也可以使用.updateMany() ):
this.siteModel.update({},
[{
$set: {
'infobox.levels': [{ infobox1: { $mergeObjects: ['$infobox', { 'levels': [] }] } },
{ infobox2: { $mergeObjects: ['$infobox', { 'levels': [] }] } }]
}
}], { multi: true })
参考: .update()
收集数据:
/* 1 */
{
"_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
"data" : 1,
"name" : "noName",
"infobox" : {
"coordx" : 2,
"coordy" : 2,
"midpoint" : {
"coordx" : 1,
"coordy" : 1
}
}
}
/* 2 */
{
"_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
"data" : 2,
"name" : "yesName",
"infobox" : {
"coordx" : 4,
"coordy" : 4,
"midpoint" : {
"coordx" : 2,
"coordy" : 2
}
}
}
更新操作后数据库中的文档:
/* 1 */
{
"_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
"data" : 1,
"name" : "noName",
"infobox" : {
"coordx" : 2,
"coordy" : 2,
"midpoint" : {
"coordx" : 1,
"coordy" : 1
},
"levels" : [
{
"infobox1" : {
"coordx" : 2,
"coordy" : 2,
"midpoint" : {
"coordx" : 1,
"coordy" : 1
},
"levels" : []
}
},
{
"infobox2" : {
"coordx" : 2,
"coordy" : 2,
"midpoint" : {
"coordx" : 1,
"coordy" : 1
},
"levels" : []
}
}
]
}
}
/* 2 */
{
"_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
"data" : 2,
"name" : "yesName",
"infobox" : {
"coordx" : 4,
"coordy" : 4,
"midpoint" : {
"coordx" : 2,
"coordy" : 2
},
"levels" : [
{
"infobox1" : {
"coordx" : 4,
"coordy" : 4,
"midpoint" : {
"coordx" : 2,
"coordy" : 2
},
"levels" : []
}
},
{
"infobox2" : {
"coordx" : 4,
"coordy" : 4,
"midpoint" : {
"coordx" : 2,
"coordy" : 2
},
"levels" : []
}
}
]
}
}
只需使用.
创建一个新的对象键。
Site.levels = {}
Site.levels.infobox1 = Site.infobox
Site.levels.infobox2 = Site.infobox
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.