[英]MongoDB: Update nested data, but avoid multiple objects
I try to insert some data into an existing document: 我尝试将一些数据插入现有文档中:
Graph.update(
{ id: id },
{
$push: {
tooltips: {
element: Session.get('tooltipID'),
text: text
}
}
}
);
This is working quite well, but if there is already data in tooltips, this one should be updated instead of adding a new object, as there can only be a unique object for a unique element (tooltipID). 这工作得很好,但是如果工具提示中已经有数据,则应该更新此数据而不是添加新对象,因为对于唯一元素(tooltipID)只能有一个唯一对象。
I want to avoid these multiple entries for the same element-value in tooltips. 我想避免在工具提示中针对相同的元素值使用这些多个条目。
{
"_id" : "c4bKur6TKcgFHGLZZ",
"data" : "[]",
"tooltips" : [
{
"element" : "2d4edaaf",
"text" : "Lorem"
},
{
"element" : "2d4edaaf",
"text" : "ipsum"
}
]
}
But it should be possible to have more then one object in tooltips, if element is really unique... 但是如果element确实是唯一的,那么在工具提示中应该可以有多个对象。
I tried to add a upsert:true
to the update(), but that doesn't work. 我试图将
upsert:true
添加到update(),但这不起作用。
Definitely upsert
won't work with embedded document. 绝对不能在嵌入式文档中使用
upsert
。
One approach can be 一种方法可以是
Graph.update({id:id},
{
$addToSet: {
'tooltips': {
element: Session.get('tooltipID'),
text: text
}
}
})
It will ensure no duplicate on tooltips; 它将确保在工具提示上没有重复;
similarly you can use $set
同样,您可以使用
$set
Graph.update({
id:id,
'tooltips.element': Session.get('tooltipID')
},
{
$set: {
'tooltips.$.text':text
}
})
or you can pull before push 或者你可以在推之前拉
Graph.update({
"id":id
}, {
$pull: {
'tooltips': {
"element": Session.get('tooltipID')
}
}
})
Graph.update(
{ id: id },
{
$push: {
tooltips: {
element: Session.get('tooltipID'),
text: text
}
}
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.