game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
}]
我有一个像上面一样的领域。我想检查传入的数据,以避免值id
重复。
incomingg_dataA: {
id: 'HUH',
name: 'Dota2'
story: 'hmmm'
}
像这种情况一样,如果incomingg_dataA
包含相同的idHUH
。我想将该值用于$addToSet
。如果id不同
incomingg_dataB: {
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}
那么,它将是
game_data: [{
id: 'HUH',
name: 'GTA'
story: 'ahhhh'
},
{
id: 'HUUUH',
name: 'Dota2'
story: 'hmmm'
}];
我可以将整个文档作为$addToSet
,但我有点担心有人会更改story
的部分,它仍然会被注册。
有没有什么方法可以用$addToSet
做到这一点,或者我只需要执行.find((和回调函数?
您必须在查找查询中添加$ne
条件,并使用想要避免重复的id
值。
db.col.update({
// All the find conditions you want
// Plus the below condition
"game_data.id": {"$ne": incomingg_dataB['id']}, // Updated only when the `id` is not already present in the array
}, {
"$push": {
"game_data": incomingg_dataB,
}
})